我是新来的使用协程,并且在运行此函数时出现和超出范围数组错误。我希望这是一个简单的问题,包含在这个函数中,也许我错误点屈服,或需要使用path.count -1。在寻路期间获取参数超出范围协程
public void UpdatePath() {
the.pathFinder.FindPath (my);
Vector3[] pathVectors = new Vector3[my.path.Count + 1];
pathVectors [0] = (Vector3)my.transform.position;
if (my.path.Count > 0) {
for (int i = 0; i < my.path.Count; i++)
pathVectors [i + 1] = my.path [i].transform.position;
}
my.pathLine.SetVertexCount (my.path.Count + 1);
my.pathLine.SetPositions(pathVectors);
StopCoroutine("FollowPath");
StartCoroutine("FollowPath");
}
IEnumerator FollowPath() {
Vector3 currentWayPoint = my.path [0].transform.position;
while (true) {
Vector2 heading = the.Heading (my.transform.position, currentWayPoint);
if (heading.sqrMagnitude < 0.4) {
targetIndex++;
if (targetIndex >= my.path.Count) {
print ("On yield break - TargetIndex is " + targetIndex + " and my.path.Count is " + my.path.Count);
yield break;
}
print ("On assigning currentWayPoint - TargetIndex is " + targetIndex + " and my.path.Count is " + my.path.Count);
currentWayPoint = my.path [targetIndex].transform.position;
}
my.pathGoal = ((heading).sqrMagnitude > 1f) ? heading.normalized * my.speed : heading * my.speed;
yield return null;
}
}
我已经打印日志来检查targetIndex对my.path.Count。据我的理解,在第二个打印日志中,targetIndex不能等于或大于my.path.Count,但在日志中,我得到“在分配currentWayPoint - TargetIndex是1和我的。 path.Count是1“。我意识到这是为什么我得到超出范围的异常,但我不明白如果TargetIndex等于my.path.Count代码是如何可达的。在收益率突破之间是否可能发生其他事情?行和打印日志?协程与其他可能冲突的代码同时运行?
我测试了你的代码,它工作得很好。至少这个问题不在你发布的方法中。 –