暂停循环允许Coroutine / Loop完成图形问题



我试图将角色移动瓷砖一个一个位置。发生的事情是单击位置,然后代码找到到达该位置的路径,并一次移动一个瓷砖直到达到位置。我的路径代码正常工作,它在阵列列表中(不要判断)。然后,我将数组列表插入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;
    }
}

现在,我的主要问题是它通过整个循环,然后从开始位置到末端位置,然后跳过图形,以从第一个瓷砖到第二个瓷砖到第三个瓷砖,等等。需要做的就是暂停循环,以便在循环继续之前让第一个Coroutine完成并启动第二个Coroutine(依此类推)。我已经尝试了在Google(Thread.Sleep()Yield Return WaitForSeconds())中发现的一些内容,但似乎没有用。...任何帮助都将不胜感激。

我需要做的就是暂停循环,让第一个Coroutine完成 在循环继续并启动第二个Coroutine之前(依此类推) 等等)

您剩下的答案不正确。就像Algorherthm所说的那样,您只等待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]));
    }
}

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

为了防止这种情况,您将必须删除循环并将变量移到方法之外,并且每次更新周期发生时,JSUT将角色移动一个步骤。向位置方法的移动看起来有点像这样。只要s小于Path.Count,就必须在每个更新中调用它。这个想法是,您必须"以步数"进行循环,而不是一次一次通话。

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

我要做的就是将ienumerator函数放在ienumerator函数中,以至于我可以设置延迟:

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

最新更新