需要帮助 我可以在void Update()中执行此操作吗?
public float waitTime = 3f;
float timer;
void Update () {
// I will do anything here then,
timer += Time.deltaTime; // start counting
// If timer become 3 seconds
if (timer > waitTime) {
timer = 0f; // to reset timer back to 0 again
}
// I will do the next command here then,
timer += Time.deltaTime; // start counting again
// If timer become 3 seconds
if (timer > waitTime) {
timer = 0f; // to reset timer back to 0 again
}
// I will do the next command here then so on,
}
或许还有另一种方式?再次需要帮助
答案 0 :(得分:3)
不,那不行:
在Update
中,当您到达第一个timer = 0f
时,对于函数的其余部分,您的计时器为0,因此第二个事件将永远不会触发。在下一帧,您将从顶部开始,在3秒后,再次到达第一个事件。
有几种解决方案。要使用代码获得简单的解决方案,您可以保存已执行的命令数:
public float waitTime = 3f;
private float timer;
private int currentCommand = 0;
void Update ()
{
timer += Time.deltaTime;
if (timer > waitTime)
{
timer -= waitTime; // this is more exact than setting it to 0: timer might be a bit greater than waitTime
// The first time the timer reaches 3s, it will call ExecuteCommand with argument 0
// The second time, with argument 1, and so on
ExecuteCommand(currentCommand);
currentCommand++;
}
}
private void ExecuteCommand(int command)
{
switch(command)
{
case 0: //HERE Code for command 0
return;
case 1: //HERE Code for command 0
return;
// as many as you want
}
}
另一个好方法是利用coroutines。如果你是一个初学者,协同程序有点棘手。这些功能可以在中间停止并在以后恢复。使用协程,您可以执行类似
的操作void Start ()
{
StartCoroutine("CommandRoutine");
}
private void IEnumerator CommandRoutine()
{
yield return new WaitForSeconds(waitTime);
// HER CODE FOR COMMAND 1
yield return new WaitForSeconds(waitTime);
// HER CODE FOR COMMAND 2
yield return new WaitForSeconds(waitTime);
// And so on
}
如果你不了解协同程序,我的第一个例子对你来说更容易理解,但是如果你感兴趣的话,尝试协程是一个很好的机会。