我试图在coroutine循环中使用两个yield(因为我需要在每个循环之间迭代迭代数组)。
第一个循环正常工作,所有产量都适用于适当的时间。通过第二个循环,yield return new WaitForSeconds()立即开始倒计时,而不是在它完成之前等待yield和代码(似乎)。到第三个循环时,时间全部关闭。
我尝试使用while循环而不是for,但得到了相同的结果。
TLDR:我需要在每个数组之间暂停我的数组。如何在协程中通过第一个循环后使用多个产量?
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;
}
}
答案 0 :(得分:0)
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;
}