【问题标题】:Time Delay for a process in Unity 3DUnity 3D 中进程的时间延迟
【发布时间】:2012-02-01 05:30:59
【问题描述】:

我必须延迟这个过程的发生,我在 Update 函数中调用它。 我也尝试过 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() 中给出代码时正在移动的对象正在移动,但没有停止。它正在上下移动。我不知道发生了什么!有人可以帮忙吗?请,谢谢。

【问题讨论】:

  • 您应该添加一些关于对象如何移动的信息。到目前为止,我看不出协程的使用与您的对象移动之间的关系。而且,顺便说一句,我认为这不是解决您的问题的正确方法,看看它有多复杂。
  • 使用 IEnumerator 函数,你可以通过 yield WaitForSeconds(n) 来延迟。

标签: unity3d unityscript


【解决方案1】:

我并不完全清楚您要完成什么,但我可以向您展示如何为协程设置时间延迟。对于此示例,让我们使用简单的冷却,就像您在示例中设置的一样。假设您想在游戏运行时每 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;
}

如果我完全错过了标记,那么请更新问题,详细说明您要完成的工作。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      private float seconds = 5;
      

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

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

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

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

      【讨论】:

      • 协程不会让你的电脑崩溃。
      • 协程不会让你的电脑崩溃。
      猜你喜欢
      • 2023-02-06
      • 2012-06-23
      • 2018-12-25
      • 1970-01-01
      • 2015-01-23
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多