延迟函数

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

相关推荐
冰凌糕1 小时前
Unity3D 单例模式
unity
Artistation Game1 天前
九、怪物行为逻辑
游戏·unity·游戏引擎
百里香酚兰2 天前
【AI学习笔记】基于Unity+DeepSeek开发的一些BUG记录&解决方案
人工智能·学习·unity·大模型·deepseek
dangoxiba2 天前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
先生沉默先2 天前
使用Materialize制作unity的贴图,Materialize的简单教程,Materialize学习日志
学习·unity·贴图
十画_8243 天前
Visual Studio 小技巧记录
unity·visual studio
red_redemption3 天前
cpp,git,unity学习
git·unity·游戏引擎
tealcwu3 天前
【Unity踩坑】Unity更新Google Play结算库
unity·游戏引擎
先生沉默先3 天前
unity 默认渲染管线材质球的材质通道,材质球的材质通道
unity·游戏引擎·材质
白鹭float.3 天前
【Unity AI】基于 WebSocket 和 讯飞星火大模型
人工智能·websocket·unity