【问题标题】:Unity C# Yield WaitForSeconds within For Loop Only Works OnceUnity C# Yield WaitForSeconds 在 For 循环中只工作一次
【发布时间】:2017-12-08 15:43:50
【问题描述】:

我试图在协程循环中使用两个产量(因为我需要在每个循环之间迭代出带有暂停的数组)。

第一个循环正常工作,所有收益都在适当的时间内工作。在第二个循环中, yield return new WaitForSeconds() 立即开始倒计时,而不是等待 yield 和 code 完成之前(似乎)。到第三个循环的时候,计时全部关闭了。

我尝试使用 while 循环而不是 for,但得到了相同的结果。

TLDR:我需要循环出我的数组,每个数组之间都有暂停。如何在协程中通过第一个循环使用多个 yield?

public IEnumerator doPathfinding()
{
    for (int i = 0; i < waypoint.Length; i++)
    {

        // get first waypoint from array
        var _waypoint = waypoint[i];

        // get node on A* of cloest waypoint
        closestPointOnNavmesh = AstarPath.active.GetNearest(_waypoint.transform.position, NNConstraint.Default).clampedPosition;

        // Move towards destination
        ai.destination = closestPointOnNavmesh;

        // Wait until within X range of waypoint
        yield return new WaitUntil(() => distanceReached == true);

        // Agent is now at waypoint and automatically stops. Wait 5 seconds before looping to next waypoint.
        yield return new WaitForSeconds(5f);

    }

    Debug.Log("Loop End");
}


    public override void OnUpdate()
    {

        // Get current distance to the target. If distance is less than offset, then sent event.    
        currentDistance = Vector3.Distance(go.transform.position, closestPointOnNavmesh);
        if(currentDistance <= arrivalOffset.Value)
        {
            distanceReached = true;
        }
        else
        {
            distanceReached = false;
        }


    }

【问题讨论】:

  • @ThomasWeller :在 Unity 中,WaitForSeconds 是一个用于使 coroutine 等待指定时间量的类。您可以将其视为Thread.sleep(即使不是同一件事)
  • @Hellium:好的,谢谢。
  • 在迭代之间是否将distanceReached 设置为false?你还没有真正告诉我们任何关于distanceReached...
  • distanceReached 在更新时运行,因此它会不断检查游戏对象 AI,以获取其位置。我将在底部使用代码更新原始帖子。
  • @Hellium 我认为Task.DelayThread.Sleep 更好比较

标签: c# arrays loops unity3d coroutine


【解决方案1】:

couroutine 中的代码很好,可以按预期工作。

很可能,根据您报告的问题,您同时调用了多次协程。

使用bool 来检查协程是否已经启动,如下所示:

bool isDoPathFindingRunning = false;
IEnumerator = doPathFinding();

private void Awake() {
    pathFinding = doPathfinding();
}

private void WhereeverYouStartCoroutine() {
    if (!isDoPathFindingRunning)
        StartCoroutine(pathFinding);
}

public IEnumerator doPathfinding() {
    isDoPathFindingRunning = true;
    // Do your stuff
    isDoPathFindingRunning = false;
}

【讨论】:

  • 谢谢,我试试看。我实际上只是在 start() 中调用它一次。 StartCoroutine(doPathfinding());
  • 它可能会从两个不同的游戏对象中调用,尤其是当场景中有很多 GO 时会发生错误。做一个简单的检查:注释掉协程中的所有内容,并记录 Debug.Log("doPathFinding started") 之类的内容 - 检查它是否只发生一次或多次。
猜你喜欢
  • 2015-03-02
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2018-11-09
  • 2016-06-15
  • 2016-01-09
相关资源
最近更新 更多