1.作为行为组件的脚本:Unity 中的脚本是什么?了解作为 Unity 脚本的行为组件,以及如何创建这些脚本并将它们附加到对象。
脚本相当于unity中的行为组件。与其他组件一样,脚本也可以应用于对象,并显示在inspector(检查器)中,
创建脚本并附加的方法:
1.项目面板中,右键创建,c#脚本,通过拖拽的方式,关联到相应的对象。
2.inspector面板中添加组件,然后选新脚本(new script)
3.顶部菜单,组件,脚本。
实例,输入rgb改变方块颜色,需要用到mesh renderer组件
using UnityEngine;
using System.Collections;
public class ExampleBehaviourScript : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
GetComponent<Renderer> ().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.G))
{
GetComponent<Renderer>().material.color = Color.green;
}
if (Input.GetKeyDown(KeyCode.B))
{
GetComponent<Renderer>().material.color = Color.blue;
}
}
}
2.变量和函数:什么是变量和函数?它们如何为我们存储和处理信息?
变量
蛮简单的,和c一样,比如,int x = 5;其中,等号前半部分是声明,后半部分是初始化。
函数
例如,int MultiplyByTwo(int number)第一个int是函数输出的数据类型,第二个是函数的输入类型具体可以看以前写的c语言函数部分,是一样的。
viod start()函数:当这个脚本绑定的对象进入场景时就会调用start函数
(补充:Debug.Log();获取游戏中的任意变量的值)
using UnityEngine;
using System.Collections;
public class VariablesAndFunctions : MonoBehaviour
{
int myInt = 5;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
int MultiplyByTwo (int number)
{
int ret;
ret = number * 2;
return ret;
}
}
3.约定和语法:了解编写代码的一些基本约定和语法:点运算符、分号、缩进和注释。
点运算符:常用于代码内的单词之间,作用是编写一行地址 例: 父.子
分号:作用:终止语句
缩进:并非必须,但方便阅读,特别是体现出层级关系
注释:①//单行注释
② /*hi
*这是一个多行注释
**/
③/**/
using UnityEngine;
using System.Collections;
public class BasicSyntax : MonoBehaviour
{
void Start ()
{
Debug.Log(transform.position.x);
if(transform.position.y <= 5f)
{
Debug.Log ("I'm about to hit the ground!");
}
}
}
4.IF 语句:如何使用 IF 语句在代码中设置条件。
和c语言语法一样
using UnityEngine;
using System.Collections;
public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
void TemperatureTest ()
{
// 如果咖啡的温度高于最热的饮用温度...
if(coffeeTemperature > hotLimitTemperature)
{
// ... 执行此操作。
print("Coffee is too hot.");
}
// 如果不是,但咖啡的温度低于最冷的饮用温度...
else if(coffeeTemperature < coldLimitTemperature)
{
// ... 执行此操作。
print("Coffee is too cold.");
}
// 如果两者都不是,则...
else
{
// ... 执行此操作。
print("Coffee is just right.");
}
}
}
5.循环:如何使用 For、While、Do-While 和 For Each 循环在代码中重复操作。
①while循环:while(条件){内容;}
using UnityEngine;
using System.Collections;
public class WhileLoop : MonoBehaviour
{
int cupsInTheSink = 4;
void Start ()
{
while(cupsInTheSink > 0)
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--;
}
}
②do-while循环:do{内容}while(条件);与前者有些不同,先循环,在判断条件是否符合
using UnityEngine;
using System.Collections;
public class DoWhileLoop : MonoBehaviour
{
void Start()
{
bool shouldContinue = false;
do
{
print ("Hello World");
}while(shouldContinue == true);
}
}
③for循环:for(int i=0;i<n;i++){内容};
using UnityEngine;
using System.Collections;
public class ForLoop : MonoBehaviour
{
int numEnemies = 3;
void Start ()
{
for(int i = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
}
}
④foreach
foreach的使用方法是foreach( type1 x1 in type1集合)
string [] day=new string[]{"monday","turseday","wenseday","thursday","sunday","saturday"};
foreach (string str in day)
{
Console.WriteLine(str);
}
//输出实例 monday
turseday
wenseday
thursday
sunday
saturday
6.作用域和访问修饰符:了解变量和函数的作用域和可访问性。
①作用域
以花括号为分界,如例子,alpha,beta,gamma作用域在整个类ScopeAndAccessModifiers里,而pens,crayons和answe的作用域在函数Example里。
②可访问性
类内定义的变量不同于函数内声明的变量,类内定义的变量带访问修饰符。
访问修饰符:放在数据类型前,用途是定义能看到变量或函数的位置,若其他脚本需要访问某个变量或函数,就应将其公开(public),否则,设为私有(private).
public:将变量设置为公开意味着可从类外部访问这个变量,也意味着这个变量可以在inspector中的组件上显示和编辑。
注意:要是在inspector中改变x的值,那么类上定义的变量【public 类型 x=初值;】就会被覆盖,然而,在void Start函数中,改变【x=新初值】,那么新的初值就把inspector输入的值覆盖掉。
且,在游戏运行时,修改inspector的值,当运行结束,修改的值并不会杯保存,如果有过忘记终止运行就修改inspector的经验的话,应该会了解这事。
private:只能在类内编辑
注意:在c#中,未指定访问修饰符的任意变量,默认使用私有访问修饰符。
公开函数,可以在其他类引用;私有函数,只能在本类使用。
one
using UnityEngine;
using System.Collections;
public class ScopeAndAccessModifiers : MonoBehaviour
{
public int alpha = 5;
private int beta = 0;
private int gamma = 5;
private AnotherClass myOtherClass;
void Start ()
{
alpha = 29;
myOtherClass = new AnotherClass();
myOtherClass.FruitMachine(alpha, myOtherClass.apples);
}
void Example (int pens, int crayons)
{
int answer;
answer = pens * crayons * alpha;
Debug.Log(answer);
}
void Update ()
{
Debug.Log("Alpha is set to: " + alpha);
}
}
another
using UnityEngine;
using System.Collections;
public class AnotherClass
{
public int apples;
public int bananas;
private int stapler;
private int sellotape;
public void FruitMachine (int a, int b)
{
int answer;
answer = a + b;
Debug.Log("Fruit total: " + answer);
}
private void OfficeSort (int a, int b)
{
int answer;
answer = a + b;
Debug.Log("Office Supplies total: " + answer);
}
}
7.Awake 和 Start:如何使用 Unity 的两个初始化函数 Awake 和 Start。
Awake和Start是两个加载脚本后自动调用的两个函数
Awake:用于在脚本与初始化之间设置任何引用。(在不启用这个脚本组件时,只能看见Awake函数)可以在启用脚本组件之前,初始化对象的设置,而不需要将脚本拆分成几个不同脚本
Start:在Awake之后调用,启用脚本之后,可以用Start启动任何所需操作。这样就可以将初始化代码的任何部分延迟到真正需要启动的时候。
例子:设置一个敌人,利用Awake获得了分配的弹药,但是想要射击的话,需要在启动脚本组件时,使用Start在定义的时间实现射击。
注意:Awake和Start在一个对象绑定脚本的生命周期内只能调用一次,因此不能通过禁用和重新启动脚本来重复执行Start函数
using UnityEngine;
using System.Collections;
public class AwakeAndStart : MonoBehaviour
{
void Awake ()
{
Debug.Log("Awake called.");
}
void Start ()
{
Debug.Log("Start called.");
}
}
8.Update 和 FixedUpdate:如何用 Update 和 FixedUpdate 函数实现每帧的更改,以及它们之间的区别。
Update:unity最常用的函数之一,脚本中使用它,会在每一帧都调用一次,所以,在需要变化或调整时,都需要它来实现。例如,非物理对象的移动,简单的计时器,输入检测等等。
注意:Update并不是按照固定时间调用的,如果某一帧比下一帧的处理时间长,调用的时间间隔就会不同。
FixedUpdate:与Update类似,不同:按固定时间调用,间隔相同。调用 FixedUpdate,会进行所有所需的物理运算,影响刚体(物理对象)的动作都应该用FixedUpdate执行。在FixedUpdate循环中编写物理脚本最好使用力来定义移动。
using UnityEngine;
using System.Collections;
public class UpdateAndFixedUpdate : MonoBehaviour
{
void FixedUpdate ()
{
Debug.Log("FixedUpdate time :" + Time.deltaTime);
}
void Update ()
{
Debug.Log("Update time :" + Time.deltaTime);
}
}
9.矢量数学:矢量数学入门以及有关点积和叉积的信息。
在unity中,使用向量来定义网格,方向等。
向量:有长度(用直角三角形两边平方之和等于第三边平方来计算),有方向(x,y,z)
注意:unity使用左手坐标系。
① Vector3.magnitude:unity为了方便上图那种的计算,引入了这个函数来帮助开发者。
②Dot Products(点积):(Ax*Bx)+(Ay*By)+(Az*Bz)=Dot Products 比如,求a,b是否垂直,则计算它们的dot products是否为0.
运用:例如,飞机模拟器,检查场景的上向量和飞机向前向量的关系,如果点积为0,说明垂直,飞机阻力最小,若点积变大,说明飞机在爬升,阻力逐渐加大,如果负值加大,那么说明在俯冲。
Vector3.Dot(VectorA,VectorB)
③Cross Products(叉积):以不同的方式组合两个向量,计算出另一个向量。是与两个向量垂直的向量
运用:确定围绕哪个轴加扭矩,已知坦克炮塔目前朝向,和目标方向,就可以对2个向量进行叉积运算,确定对哪个轴施加转动扭矩
Vector3.Cross(VectorA,VectorB)
10.启用和禁用组件:如何在运行时通过脚本启用和禁用组件。
启用和禁用组件:enabled标记
using UnityEngine;
using System.Collections;
public class EnableComponents : MonoBehaviour
{
private Light myLight;
void Start ()
{
myLight = GetComponent<Light>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}
myLight.enabled=false;关闭
myLight.enabled=true;开启
myLight.enabled=!myLight.enabled;切换
11.激活游戏对象:
如何使用 SetActive 和 activeSelf/activeInHierarchy 单独处理以及在层级视图中处理场景内部游戏对象的活动状态。
使用脚本激活或停用游戏对象:可以使用SetActive函数
停用父对象,子对象都会被停用,因为它所在的层级已经停用,但是子对象在此层次结构中仍然活跃。
using UnityEngine;
using System.Collections;
public class ActiveObjects : MonoBehaviour
{
void Start ()
{
gameObject.SetActive(false);
}
}
检查是否活跃
using UnityEngine;
using System.Collections;
public class CheckState : MonoBehaviour
{
public GameObject myObject;
void Start ()
{
Debug.Log("Active Self: " + myObject.activeSelf);
Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy);
}
}
12.Translate 和 Rotate:
如何使用两个变换函数 Translate 和 Rotate 来更改非刚体对象的位置和旋转。
Translate :平移
void Update(){
transform.Translate(new Vector3(0,0,1));
}
每帧沿z轴移动单位1,速度比较快
public float moveSpeed = 10f;
void Update(){
transform.Translate(Vector3.forword*moveSpeed*Time.deltaTime);
}
Vector3.forword:沿z轴向前移动。
Time.deltaTime:以秒为单位,不以帧
using UnityEngine;
using System.Collections;
public class TransformFunctions : MonoBehaviour
{
public float moveSpeed = 10f;
public float turnSpeed = 50f;
void Update ()
{
if(Input.GetKey(KeyCode.UpArrow))
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.DownArrow))
transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.LeftArrow))
transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.RightArrow))
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
}
}
1if 当按↑按钮时,向前移动
Input.GetKey(KeyCode.UpArrow),输入键盘的↑键
2if 当按↓按钮时,向后移动
3if 当按←按钮时,向左旋转
Rotate:旋转 ,Vector3.up沿着向上的轴
4if 当按→按钮时,向右旋转
13.