【发布时间】: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.Delay比Thread.Sleep更好比较
标签: c# arrays loops unity3d coroutine