Unity 3D 中进程的时间延迟

问题描述 投票:0回答:3

我必须给出该过程发生的延迟,我在更新函数中调用该延迟。 我也尝试过 CoUpdate 解决方法。这是我的代码:-

function Start() 
{
  StartCoroutine("CoStart"); 
} 
function CoStart() : IEnumerator 
{ 
  while(true) 
  { 
    yield CoUpdate(); 
  } 
} 
function CoUpdate() 
{ 
  //I have placed the code of the Update(). 
  //And called the wait function wherever needed. 
} 
function wait() 
{ 
   checkOnce=1; //Whenever the character is moved. 
   yield WaitForSeconds(2); //Delay of 2 seconds. 
}

当第三人称控制器(这是另一个对象)移出边界时,我必须移动对象。我在我的代码中包含了“yield”。但是,发生的问题是:当我在 Update() 中给出代码时正在移动的对象正在移动,但没有停止。而且它正在上下移动。我不知道发生了什么事!有人可以帮忙吗?拜托,谢谢。

unity-game-engine unityscript
3个回答
0
投票

我不完全清楚你想要完成什么,但我可以向你展示如何为协程设置时间延迟。对于此示例,让我们进行简单的冷却,就像您在示例中设置的那样。假设您希望在游戏运行时每 2 秒连续执行一次操作,可以对代码进行轻微修改。

function Start()
{
   StartCoroutine(CoStart);
}

function CoStart() : IEnumerator
{
   while(true)
   {
      //.. place your logic here

      // function will sleep for two seconds before starting this loop again
      yield WaitForSeconds(2);   
   }
}

您还可以使用其他逻辑来计算等待时间

function Start()
{
   StartCoroutine(CoStart);
}

function CoStart() : IEnumerator
{
   while(true)
   {
      //.. place your logic here

      // function will sleep for two seconds before starting this loop again
      yield WaitForSeconds(CalculateWait());   
   }
}

function CalculateWait() : float
{

   // use some logic here to determine the amount of time to wait for the 
   // next CoStart cycle to start
   return someFloat;
}

如果我完全没有达到目标,那么请更新问题,并提供有关您想要完成的任务的更多详细信息。


0
投票

我不是 100% 确定我理解你的问题,但如果你想在另一个对象超出范围时启动一个对象移动,那么只需在第一个对象中对第二个对象进行引用,并且当第一个对象超出范围时边界(在第一个对象的更新中检查这一点)在第二个对象上调用一些公共函数 StartMove。


-3
投票

我不会建议使用协程。它有时会使您的计算机崩溃。只需定义一个变量并递减它即可。示例:

private float seconds = 5;

然后做任何你想延迟的地方:

seconds -= 1 * Time.deltaTime;
if(seconds <= 0) {your code to run}

这将导致 5 秒的延迟。您可以将 5 更改为任何值来更改秒数。您还可以通过更改 1 的值来加快递减速度。(当您想通过使用同一变量同步 2 个延迟操作时,这非常有用)

希望这有帮助。快乐编码:)

© www.soinside.com 2019 - 2024. All rights reserved.