延迟函数

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

相关推荐
w-白兰地8 小时前
【Addressable远端加载资源】
unity·addressable·资源加载
小张不爱写代码11 小时前
[Unity 技巧] 如何自定义 Inspector 变量显示名称 (CustomLabel)
unity·游戏引擎
Sator112 小时前
Unity开发中常用的随机方法扩展
unity
dzj202112 小时前
Unity中使用LLMUnity遇到的问题(五)——主要脚本的继承关系+用DuckDB对知识库升级的思考
unity·向量数据库·向量搜索·duckdb·llmunity
地狱为王16 小时前
Unity使用Spleeter分离人声和伴奏
unity·游戏引擎·spleeter
在路上看风景19 小时前
26. Texture和Sprite
unity
lllljz21 小时前
Blender导出模型到Unity或UE5引擎材质丢失模型出错
unity·ue5·游戏引擎·blender·材质
_乐无1 天前
Unity 发布 Android 安卓端所有文件可读写
android·unity·游戏引擎
JIes__2 天前
Unity(二)——核心系统
unity·游戏引擎
独处东汉2 天前
freertos开发空气检测仪之按键输入事件管理系统设计与实现
人工智能·stm32·单片机·嵌入式硬件·unity