2014-07-21 40 views
0

好几乎我想要做的是让我的程序等待预定的时间,然后将字符移动到网格上的另一个点(它由“panel_x”和“panel_y”变量标记)。相反,它会等待,然后移动每个框架周围的角色...我不知道我做错了什么。我相信我需要一个协程,但我可能是错的。为什么我的程序不能像我需要的那样等待?

//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); 
     } 
    } 

回答

1

更新在每一帧上运行。这里发生的事情是,你在每一帧都会调用Wait(),这将在无限循环中运行多个实例。

我相信你要做的是每3秒更改x和y值。 如果是这样,尝试这样的事情。

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返回帧之间所经过的时间,因此它可以通过求和它的每一个帧被用作一个定时器。当3秒钟过去后,我们将计时器重置为0并运行我们的方法。

+1

谢谢!我的Twitter上的某个人告诉我只需将StartCoroutine放入启动方法中即可使用,但这个提示给我很多次,所以下次我需要使用这种方法! –

0

您是否修改过那个HP?如果HP不是0,那么StartCoroutine(Wait())将在每次执行Update()时被调用。这就是为什么你会得到奇怪的结果。

-1

您的功能似乎没有任何参数,所以我可以为您提供其他方法,如Invoke作为替代。

Invoke(x, y)在一定的延迟时间后执行一个功能。你的情况,例如:

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); 
} 

只是为了您的信息,也有InvokeRepeating(x, y, z)这也许你不会在这种情况下需要。
它在y延迟调用函数x之后每隔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); 
} 
相关问题