延迟函数
Destory函数:
public static void Destroy(Object obj, [DefaultValue("0.0F")] float t);
Invoke函数:
public void Invoke(string methodName, float time);
挂个空物体测试一下:
public class DelayTest : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){Invoke("TestInvoke",5);}// Update is called once per framevoid Update(){if(Input.GetKeyDown(KeyCode.A))transform.gameObject.SetActive(false);if(Input.GetKeyDown(KeyCode.B))Destroy(this);if(Input.GetKeyDown(KeyCode.C))Destroy(this.gameObject);}void TestInvoke(){transform.gameObject.SetActive(true);Debug.Log("TestInvoke");}
}
发现按下A键使物体失活,延迟函数Invoke仍会执行,但当前脚本或者脚本的游戏物体被销毁时,Invoke不会执行
我们可以通过CancelInvoke函数来取消Invoke:
public void CancelInvoke();
无参情况下是取消当前代码内所有Invoke函数
public void CancelInvoke(string methodName);
InvokeRepeating:重复调用Invoke
public void InvokeRepeating(string methodName, float time, float repeatRate);
time表示多少秒后执行methodName
repeatRate表示重复执行methodName的时间间隔