monoBehavior內置的延時執行函數方法Invoke和InvokeRepeating

public void Invoke(string methodName,float time)

實現將某個函數延遲time秒後執行。

官方例子:

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    // Launches a projectile in 2 seconds

    Rigidbody projectile;

    void Start()
    {
        Invoke("LaunchProjectile", 2);
    }

    void LaunchProjectile()
    {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5;
    }
}
上面的例子會執行兩秒後調用LaunchProjectile方法。

public void InvokeRepeating(string methodName,float time, float repeatRate)

實現將某個函數延遲time秒後執行,延遲repeatRate重新執行Invoke,無限次循環。

官方例子:

using UnityEngine;
using System.Collections.Generic;

// Starting in 2 seconds.
// a projectile will be launched every 0.3 seconds

public class ExampleScript : MonoBehaviour
{
    public Rigidbody projectile;

    void Start()
    {
        InvokeRepeating("LaunchProjectile", 2.0f, 0.3f);
    }

    void LaunchProjectile()
    {
        Rigidbody instance = Instantiate(projectile);

        instance.velocity = Random.insideUnitSphere * 5;
    }
}
上面的例子會執行兩秒後調用LaunchProjectile方法,0.3秒後重新執行2秒後調用LaunchProjectile方法,這是一個完整的循環,之後會無限執行這個循環。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章