实例化与销毁
实例化
public GameObject box;
void Update(){
if (Input.GetKeyDown(KeyCode.Space)){
Vector3 position = new Vector3(Random.Range(40.5f, 59.5f), 0.5f, Random.Range(-9.5f, 9.5f));
GameObject.Instantiate(box, position, Quaternion.identity);
}
}
销毁
//直接挂载到预制体上
void Start()
{
GameObject.Destroy(gameObject, Random.Range(1.0f, 3.0f));
}
invoke函数调用
void Start(){
Invoke("Create", 2); //2秒后调用
InvokeRepeating("Create", 5, 0.5f); //5秒后调用,每0.5秒重复一次
}
void Update(){
if (Input.GetKeyDown(KeyCode.Space){
CancelInvoke("Create"); //取消调用Create()函数
CancelInvoke(); //取消全部调用
}
}
void Create(){}
消息发送
void OnTriggerEnter(){
if(coll.gameObject.tag == "Gold"){
//调用coin上的AddScore函数
coll.gameObject.SendMessage("AddScore");
coll.gameObject.GetComponent<Gold>().AddScore();
}
}
协同程序
void Start(){
Debug.Log("1");
Debug.Log("2");
StartCoroutine("task3");
Debug.Log("4");
}
void Update(){
if (Input.GetKeyDown(KeyCode.Space)){
StopCoroutine("task3");
}
}
IEnumerator task3(){
yield return new WaitForSeconds(2);
Debug.Log("3");
yield return new WaitForSeconds(2);
Debug.Log("5");
}
脚本生命周期
Test
public GameObject prefabCube;
private GameObject myCube;
void Update () {
if(Input.GetKeyDown(KeyCode.Space)){
myCube = GameObject.Instantiate (prefabCube, Vector3.zero, Quaternion.identity) as GameObject;
}
if(Input.GetKeyDown(KeyCode.A)){
GameObject.Destroy (myCube);
}
}
CubeLife
void Awake(){} //只执行一次
void OnEnable(){} //脚本组件启用时执行一次
void Start(){}
void FixedUpdate(){}
void Update(){}
void LateUpdate(){} //在update之后执行,执行次数永远比update多一次
void OnGUI(){} //旧版渲染GUI方法,已弃用
void OnDisable(){} //脚本组件禁用时执行一次,而且必须在OnDestroy前
void OnDestroy(){} //游戏物体被销毁时执行一次
工具类
Screen类
属性
Screen.height
:静态只读,屏幕高度
Screen.width
:静态只读,屏幕宽度
开发模式下返回Game视图的宽度和高度,项目打包后再运行是设备屏幕的宽度和高度
Mathf结构体
Mathf.Abs()
Mathf.Max(,)
Mathf.Min(,)
Mathf.Round()
Mathf.Lerp(float a, float b, float t)
:插值运算
基于t的值返回a和b之间的值
t = 0 返回a
t = 1 返回b
//一个数从0插值运算到10
num = MathdLerp(num, 10, deltaTime);
Time类
Time.time
:静态只读,游戏运行时长
Time.deltaTime
静态只读,时间增量。渲染完上一帧所耗时间
Time.timeScale
静态写读,时间缩放(值为1正常,值为0暂停)