【发布时间】:2021-08-15 12:48:36
【问题描述】:
InvokeRepeating("MoveEnemies", 1.0f, ratioAlive);
我在 start 方法中调用了它。但是,它只会使用原始的 ratioAlive 值运行。
如果我在更新中运行它,它会运行我不想要的每一帧。
【问题讨论】:
标签: c# unity3d game-physics
InvokeRepeating("MoveEnemies", 1.0f, ratioAlive);
我在 start 方法中调用了它。但是,它只会使用原始的 ratioAlive 值运行。
如果我在更新中运行它,它会运行我不想要的每一帧。
【问题讨论】:
标签: c# unity3d game-physics
如果您确实需要每 N 秒调用一次函数(其中 N != const)并且您无法通过 events 实现它,那么您可以尝试使用 Coroutine。
它会每隔 N 秒自动调用一次Foo(),但 N 可以在此类或其他类中更改:
public float Delay; // Your "N"
private IEnumerator InvokeRepeatedly () { // Coroutine that invokes the function
while (true) {
Foo(); // Call
yield return new WaitForSeconds(Delay);// Wait
}
}
private void Foo () {...} // The function
你也可以发送一些参数:
private IEnumerator InvokeRepeatedly (int a, bool b) {
while (true) {
Foo(a, b);
yield return new WaitForSeconds(Delay);
}
}
private void Foo (int a, bool b) {...}
此外,您可以定义自己的委托(或使用现有的)并通过协程调用不同的函数,除非它们的参数或返回值不同。
delegate void SomeDelegate(float a, bool b); // Defininf delegate type
private IEnumerator InvokeRepeatedly (SomeDelegate func, float a, bool b) {
func(a, b); // Call function sent as an argument
}
private void Func1 (float num, bool isTrue) {...} // First fucntion
private void Func2 (float num, bool isTrue) {...} // Second function
// Whatever void function that takes these arguments would be appropriate.
如果是这样,你可以这样称呼它:
SomeDelegate func = new SomeDelegate(Func1); // Define a delegate instance
StartCoroutine(InvokeRepeatedly(func, 1.0f, true)); // Call coroutine that will call function
【讨论】: