2017-03-08 85 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. –

相關問題