延迟函数

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 update
    void Start()
    {
        Invoke("TestInvoke",5);
    }

    // Update is called once per frame
    void 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

cs 复制代码
public void InvokeRepeating(string methodName, float time, float repeatRate);

time表示多少秒后执行methodName

repeatRate表示重复执行methodName的时间间隔

相关推荐
℡枫叶℡9 小时前
Unity - 全局配置Unity工程的资源检索的目录
unity·资源检索配置
mxwin9 小时前
Unity URP 下 TBN 矩阵学习 切线空间、tangent.w 与镜像 UV 的那些坑
学习·unity·矩阵·shader
程序猿多布9 小时前
Unity导表工具解决方案-Luban使用教程
unity·luban
mxwin10 小时前
Unity URP Shader 混合模式完全指南
unity·游戏引擎
mxwin10 小时前
Unity URP 下 HDR 与 Tonemapping 的 Shader 意识
unity·游戏引擎
沉默金鱼11 小时前
U3D高级编程:主程手记——第二章2.1读书笔记
unity·游戏引擎
mxwin1 天前
Unity Shader 深度写入与关闭ZWrite Off · 半透明排序 · 粒子穿插
unity·游戏引擎·shader
张老师带你学1 天前
宇宙飞船完整Unity项目
科技·游戏·unity·游戏引擎·模型
mxwin1 天前
Unity URP 下的流体模拟 深入解析 Navier-Stokes 方程与浅水方程的数学原理
unity·游戏引擎
mxwin1 天前
Unity Shader 深度重建世界坐标
unity·游戏引擎·shader