延迟函数

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

相关推荐
jtymyxmz7 小时前
《Unity Shader》12.5 Bloom 效果
unity·游戏引擎
jtymyxmz9 小时前
《Unity Shader》12.6 运动模糊
unity·游戏引擎
jtymyxmz11 小时前
《Unity Shader》12.4.2 实现
unity·游戏引擎
sindyra13 小时前
Unity UGUI 之 Canvas Scaler
unity·游戏引擎
在路上看风景17 小时前
2.Square Grid
unity
程序猿阿伟17 小时前
《突破Unity热更新瓶颈:底层函数调用限制与生态适配秘籍》
unity·游戏引擎
在路上看风景19 小时前
13. UGUI合批
unity
jtymyxmz1 天前
《Unity Shader》12.2调整屏幕的亮度、饱和度和对比度
unity·游戏引擎
AllBlue2 天前
unity嵌入安卓界面,如何显示状态
android·unity·游戏引擎
tealcwu2 天前
【Unity技巧】实现在Play时自动保存当前场景
java·unity·游戏引擎