[英]Why doesn't my program wait like I need it to?
Ok pretty much what I am trying to do is have my program wait a predetermined amount of times then move the character to another spot on the grid (which is notated by the "panel_x" and "panel_y" variables). 好的,我想做的是让程序等待预定的时间,然后将字符移动到网格上的另一个位置(由“ panel_x”和“ panel_y”变量表示)。 Instead it waits and then moves the character around every frame...Im not sure what I am doing wrong.
相反,它会等待,然后在每个帧中移动角色...我不确定我在做什么错。 I believe I need a coroutine, but I may be wrong.
我相信我需要协程,但我可能错了。
//How I am calling the coroutine
void Update()
{
if(HP != 0)
{
StartCoroutine(Wait());
}
}
//The Coroutine I need to run to move my character
//around...I need this to run until the character's
//hp reaches 0.
IEnumerator Wait()
{
while(true)
{
//I need it to wait...
yield return new WaitForSeconds(3);
//Then move the character to another
//grid...
panel_x = Random.Range(1, 4);
panel_y = Random.Range(1, 4);
}
}
Update runs on every frame. 更新在每个框架上运行。 What's happening here is that you're calling Wait() on every frame which will run multiple instances in an infinite loop.
这里发生的是,您在每帧上调用Wait(),它将在无限循环中运行多个实例。
I believe what you're trying to do is change the x and y values every 3 seconds. 我相信您要执行的操作是每3秒更改一次x和y值。 If so, try something like this.
如果是这样,请尝试这样的操作。
float timer = 0.0f;
void Update()
{
if (HP != 0)
{
timer += Time.deltaTime;
if (timer >= 3)
{
panel_x = Random.Range(1, 4);
panel_y = Random.Range(1, 4);
timer = 0;
}
}
}
Time.deltaTime returns the time passed between frames so it can be used as a timer by summing it every frame. Time.deltaTime返回帧之间经过的时间,因此可以通过将每个帧相加来用作计时器。 When 3 seconds has passed, we reset the timer to 0 and run our method.
经过3秒后,我们将计时器重置为0并运行我们的方法。
Did you modify that HP
ever after? 您是否曾经修改过该
HP
? If HP is not 0, then the StartCoroutine(Wait())
will be called every time Update()
is executed. 如果HP不为0,则每次执行
Update()
时都会调用StartCoroutine(Wait())
。 That is why you get the weird result. 这就是为什么您得到奇怪的结果的原因。
Your function doesn't seem to take any parameters, so I can provide you other method like Invoke
as an alternative. 您的函数似乎没有任何参数,因此我可以为您提供其他方法,例如
Invoke
。
Invoke(x, y)
executes a function after a certain amount of seconds delay. 在一定的秒数延迟后
Invoke(x, y)
执行一个函数。 In your case for example: 以您的情况为例:
void Update(){
if(HP != 0)
Invoke("MoveChar", 3); //execute MoveChar() after 3 seconds
}
MoveChar(){
panel_x = Random.Range(1,4);
panel_y = Random.Range(1,4);
}
Just for your info, there is also InvokeRepeating(x, y, z)
which maybe you won't need in this case. 仅出于您的信息考虑,还有
InvokeRepeating(x, y, z)
,在这种情况下您可能不需要。
It repeats every z seconds after function x being called with y delay. 在函数x被延迟y调用之后,它每z秒重复一次。
void Start(){
//execute MoveChar() after 3 seconds and call the
//function again after 0.5 seconds repeatedly
InvokeRepeating("MoveChar", 3, 0.5);
}
MoveChar(){
panel_x = Random.Range(1,4);
panel_y = Random.Range(1,4);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.