如何在 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));
我希望“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));