一。克隆游戏对象
//在预设体的位置克隆游戏对象
GameObject go1=Instantiate(cube);
//在固定位置克隆游戏对象
//Quaternion.identity 游戏对象不旋转:Quaternion(0,0,0,0)
GameObject go2 =Instantiate(cube,new Vector3(0,0,5),Quaternion.identity);
二。销毁游戏对象
Destroy(go1); //直接销毁对象go1
Destroy(go2,3); //停3秒后销毁对象go2
三。查找游戏对象
通过名称来查找游戏对象
GameObject cube1=GameObject.Find("Player");
GameObject cube2=GameObject.FindWithTag("Player");
四。添加,获取组件
//1、把Move这个脚本加到cube这个游戏对象上
cube.AddComponent("Move");
//2、给游戏物体添加刚体
cube.AddComponent("Rigidbody");
//3、给游戏物体添加球体碰撞器
cube.AddComponent("BoxCollider");
//1、获取脚本组件Move
Move m=cube.GetComponent<Move>();
//2、获取刚体组件
Rigidbody r=cube.GetComponent<Rigidbody>();
五。Random
float a=Random.value; //返回0.0(包括)到1.0(包括)之间的数。
int b=Random.Range(0,100) ; //包括最小但不包括最大
float c=Random.Range(0.0f,5.5f); //包括最大和最小
六。Input
- 鼠标事件
GetMouseButton(0):按下鼠标左键不动,程序会一直运行,松开左键程序停止运行。
GetMouseButton(2):按下鼠标中键不动,程序会一直运行,松开中键程序停止运行。
GetMouseButton(1):按下鼠标右键不动,程序会一直运行,松开右键程序停止运行。
GetMouseButtonDown(0):按下鼠标左键时,程序运行一次
GetMouseButtonDown(1):按下鼠标右键时,程序运行一次
GetMouseButtonUp(2):按下鼠标中键时,程序不运行,松开中键时,程序运行一次。
if(Input.GetMouseButton(0)){
执行语句;
}
- 键盘事件
GetKey 当通过名称指定的按键被用户按住时返回true
GetKeyDown 当用户按下指定名称的按键时的那一帧返回true。
GetKeyUp 在用户释放给定名字的按键的那一帧返回true。
GetAxis("Horizontal")和GetAxis("Vertical") 水平轴和垂直轴
if(Input.GetKey("Down")){
执行语句;
}
案例:用方向键或WASD键来模拟物体移动
float speed = 3f;
void Update () {
//float h = Time.deltaTime * speed;
//按下WSAD键使游戏对象前后左右移动
/*if (Input.GetKey(KeyCode.A))
{
transform.Translate(new Vector3(-h, 0, 0));
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(new Vector3(h, 0, 0));
}
if (Input.GetKey(KeyCode.W))
{
transform.Translate(new Vector3(0, 0, h));
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(new Vector3(0, 0, -h));
}*/
//Horizontal
//Vertical
float h= Input.GetAxis("Horizontal")*Time.deltaTime*speed;
float v = Input.GetAxis("Vertical") * Time.deltaTime * speed;
//transform.Translate(h, 0, v);
transform.Translate(new Vector3(h, 0, v));
}
- 自定义按钮
GetButton 根据按钮名称返回true当对应的虚拟按钮被按住时。
GetButtonDown 在给定名称的虚拟按钮被按下的那一帧返回true。
GetButtonUp 在用户释放指定名称的虚拟按钮时返回true。
案例:点击鼠标左键,给物体加一个力
if (Input.GetButtonDown("Fire1"))
{
GameObject go = Instantiate(cube);
Rigidbody r = go.GetComponent<Rigidbody>();//从预设体身上获取刚体组件
r.AddForce(0,0,10000);//给预设体加力
}
七。协程
协同程序,即将主程程序运行时同时开启另一段逻辑处理来协同当前程序的执行。换句话说,开启协同程序就是开启一个线程。
使用StartCoroutine(string methodName)可以开启一个线程。
Yield语句是一种特殊类型的Return(返回)语句,它可以确保函数在下一次被执行时,不是从头开始,而是从Yield语句处开始。
协程其实就是一个IEnumerator(迭代器)。迭代器方法运行到 yield return 语句时,会返回一个表达式并保留当前在代码中的位置。 当下次调用迭代器函数时执行从该位置重新启动。
案例:每隔3秒克隆一个立方体
public GameObject cube;
void Start () {
StartCoroutine("NewCube");
}
IEnumerator NewCube()
{
while (true)
{
Instantiate(cube);
yield return new WaitForSeconds(3f);
}
}