2017-03-08 87 views
0

所以我尝试着让一个游戏对象在三点之间来回移动,这是在C#中的统一,我在统一检查器中分配了3个游戏对象,我想让游戏对象在点之间来回移动问题是我得到一个索引超出范围错误。为什么是这样的,我该如何解决它? 对不起,可能是格格不入的mestakes。它为什么会抛出索引超出范围错误?

这里是我的代码:

public class Enamy2 : MonoBehaviour { 

    public Transform[] pointPosition; 
    public float enamySpeed; 
    private int currentPoint; 
    private bool backTracking = false; 


    // Use this for initialization 
    void Start() { 
     transform.position = pointPosition [0].position; 
     currentPoint = 0; 

    } 

    // Update is called once per frame 
    void Update() { 
     if (transform.position == pointPosition[currentPoint].position) { 
      if (backTracking) 
       currentPoint--; 
      else 
       currentPoint++; 
     } 
     if(currentPoint >= pointPosition.Length) { 
      backTracking = true; 
     } 
     transform.position = Vector3.MoveTowards (transform.position, pointPosition [currentPoint].position, Time.deltaTime * enamySpeed); 
    } 

}

回答

1

IndexOutOfRangeException发生在两种情况下:索引太大或太小。您不能在C#中使用负向索引器。你有这样的:

if(currentPoint >= pointPosition.Length) { 
     backTracking = true; 
     currentPoint = pointPosition.Length - 1; 
    } 

现在,您需要添加此直接算账:

if(currentPoint <= 0) { 
     backTracking = false; 
     currentPoint = 0; 
    } 

附加线夹紧currentPoint至边界位置,确保它是边界内下一行调用之前。

在这一点上,如果你得到一个IndexOutOfRangeException那么它会是因为pointPosition []是空的并且没有元素。

1

currentPoint变得太大。你甚至可以检查:

if(currentPoint >= pointPosition.Length) { 
    backTracking = true; 
} 

但设置backTrackingtrue身边,你不要做这件事,并在你的下一行,您使用的pointPosition[currentPoint]什么。如果它变得大于或等于pointPosition.Length它超出范围。

+0

我应该如何修改脚本,以便我能得到desiered的结果?我只做了一个星期的团结和C#,所以对我来说很难... –

+0

您需要在if语句中重置'currentPoint'。例如:'backTracking = true; currentPoint = 0;'或者你处理backTracking的方式不同。 –

+1

其实,你也必须确保'currentPoint'从不否定。添加一个if语句来关闭backTracking,如果'currentPoint'达到0. –

相关问题