【问题标题】:Pause Loop to allow for Coroutine / Loop to finish graphics Issue暂停循环以允许协程/循环完成图形问题
【发布时间】:2016-12-23 05:41:44
【问题描述】:

我正在尝试让角色将瓷砖一张一张地移动到一个位置。发生的情况是单击该位置,然后代码找到到该位置的路径并一次移动一个图块,直到它到达该位置。我有寻路代码工作,它在一个 ArrayList 中(不要判断)。然后我将数组列表插入到一个 for 循环中,如下所示:

//This function Moves Character to clicked location
void MoveToPosition(ArrayList Path)
{

    int s = 2;
    while (s < Path.Count)
    {
        Debug.Log(Path[s]);
        StartCoroutine(MoveToPositionBuffer((Vector3) Path[s]));
        s++;

    }
    ResetTiles();
}

//This does the continous Calculations Somehow
IEnumerator MoveToPositionBuffer(Vector3 Position)
{
    Vector3 StartingPosition = gameObject.transform.position;
    Vector3 EndPosition = Position;
    EndPosition[1] = StartingPosition[1];

    float counter = 0;

    while(counter < 1)
    {
        counter += Time.deltaTime;
        gameObject.transform.position = Vector3.Lerp(StartingPosition, EndPosition, counter);
        yield return null;
    }
}

现在我的主要问题是它遍历整个循环,然后从开始位置到结束位置进行 Lerping,并跳过从第一个图块移动到第二个图块到第三个图块的图形,等等。我是什么需要做的是暂停循环,让第一个协程在循环继续之前完成并启动第二个协程(依此类推)。我已经尝试了一些我在谷歌上找到的东西(Thread.Sleep(),协同程序中的Yield Return WaitForSeconds()),但它似乎不起作用....任何帮助将不胜感激。

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    我需要做的是暂停循环让第一个协程完成 在循环继续并开始第二个协程之前(依此类推 等等)

    您留下的answer 不正确。就像AlGoreRhythm 所说,您只需要等待 1 秒钟。它现在可能对您有用,但它可靠。当帧率大幅下降时,您会遇到代码无法完成运行的问题。

    删除WaitForSeconds,然后使用yield return StartCoroutine(MoveToPositionBuffer((Vector3)Path[i]));

    IEnumerator DelayForMovingLoop(ArrayList Path)
    {
        for (int i = 2; i < Path.Count; i++)
        {
            yield return StartCoroutine(MoveToPositionBuffer((Vector3)Path[i]));
        }
    }
    

    【讨论】:

      【解决方案2】:

      这两种方法都在同一个线程上运行。这意味着,将处理整个循环,并在完成后进行绘图。然而,当循环结束时,这意味着该位置将是路径上的最后一个位置。

      为了防止这种情况,您必须删除循环并将变量移到方法之外,并且每次更新循环发生时将角色移动一步。移动到位置方法可能看起来有点像这样。只要s 小于Path.Count,就必须在每次更新时调用它。这个想法是,您必须“分步”执行循环,而不是一次调用。

      private int s = 2;
      
      void MoveToPosition(ArrayList Path)
      {
         Debug.Log(Path[s]);
         StartCoroutine(MoveToPositionBuffer((Vector3) Path[s]));
         s++;
      }
      

      【讨论】:

      • 我试图这样做。简单地说,我在更新函数中放了一些代码,这就是决定它是否应该移动到下一个位置的原因......但现在它没有动画,它现在从每个方格传送到下一个方格。有什么想法吗?
      • 功能!不是错误:)
      【解决方案3】:

      我所要做的就是将一个 IEnumerator 函数放在一个 IEnumerator 函数中,这样我就可以设置一个延迟:

       IEnumerator DelayForMovingLoop(ArrayList Path)
      {
      
          for (int i = 2; i < Path.Count; i++)
          {
              StartCoroutine(MoveToPositionBuffer((Vector3)Path[i]));
              yield return new WaitForSeconds(1);
          }
      
      }
      

      【讨论】:

      • 如何等待它完成?您只需等待 1 秒。
      • 如果您查看函数“MoveToPositionBuffer()”中的 while 循环,到达下一个图块的时间总是正好一秒(稍后可以通过设置 'counter
      猜你喜欢
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      相关资源
      最近更新 更多