2017-03-31 42 views
0

我是新来的使用协程,并且在运行此函数时出现和超出范围数组错误。我希望这是一个简单的问题,包含在这个函数中,也许我错误点屈服,或需要使用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代码是如何可达的。在收益率突破之间是否可能发生其他事情?行和打印日志?协程与其他可能冲突的代码同时运行?

+0

我测试了你的代码,它工作得很好。至少这个问题不在你发布的方法中。 –

回答

0

这与协程无关。

你试着用索引比数组元素的数量较高的访问员:

for (int i = 0; i < my.path.Count; i++) 
    pathVectors [i + 1] = my.path [i].transform.position; // will fail on i = path.Count 

此外,编译器会告诉你在什么时候这个异常情况的代码,这应该很容易导致你结论您已经达到:

需要使用path.count -1

它总是一个好想在代码中尝试一下你的想法,看看它是否有效,然后再问问题。

此外,围绕此代码的if声明没有意义。

+0

如何我= path.Count如果我

+0

感谢您的评论,我试图改变这一部分,并没有什么区别,只是打破了功能。在这一行没有发生索引,它发生在... currentWayPoint = my.path [targetIndex] .transform.position; 一行,尽管如果targetIndex是=> my.path.Count,它之前的行会中断。很奇怪。 –