繁体   English   中英

如何在 Unity C# 中每 X 秒重复一个动作

[英]How to repeat an action each X seconds in Unity C#

我希望动作“randomNumber”每 30 秒发生一次。

public class INScript : MonoBehaviour
{
    int rnd;

    void Start()
    {
         Invoke("randomNumber", 30);   
    }

    public void randomNumber()
    {
        rnd = Random.Range(0, 100);
        Debug.Log(rnd);
    }
}

您可以使用InvokeRepeating来实现它。 在您的情况下,它看起来像这样:

void Start()
{
     InvokeRepeating("randomNumber", 0, 30);   
}

其中 0 是调用方法之前的初始延迟(因此,即时),30 是每 30 秒重复该方法

您将需要使用Coroutines

bool running;

IEnumerator DoWork(int time) 
{
    // Set the function as running
    running = true;
    
    // Do the job until running is set to false
    while (running)
    {
        // Do your code
        randomNumber();
        
        // wait for seconds
        yield return new WaitForSeconds(time);
    }
}

要调用它,请使用以下命令:

// Start the function on a 30 second time delay
StartCoroutine(DoWork(30));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM