延迟函数

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的时间间隔

相关推荐
谢斯2 天前
[unity]如何在unity中添加newtonsoft-json
unity·json·游戏引擎
天人合一peng2 天前
Unity标记固定颜色及投影标记
unity
云雨巫山2 天前
Unity 游戏开发性能优化全景手册
unity·智能手机·性能优化·游戏引擎
maybeyaluokenai2 天前
unity build in渲染管线概述
unity·图形渲染
云雨巫山2 天前
Unity 性能优化 · 图解全景手册
unity·性能优化·游戏引擎
Madokaly2 天前
DOTween的Vector3Plugin
unity
一梭键盘任平生3 天前
Shader入门笔记2
unity
点心的游戏开发世界3 天前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
点心的游戏开发世界3 天前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
微三云生态系统架构师-彭丹5 天前
任务卷轴积分系统架构设计:从任务状态机到合规风控的完整实现
unity·系统架构·游戏引擎