2016-04-12 29 views
0

我正在嘗試做一個關卡選擇菜單。這是我的佈局的截圖:enter image description here爲了使這項工作,這是我促成這件事情的腳本:Unity c# - 應該改變文本的腳本錯誤

using UnityEngine; 
using UnityEngine.UI; 

public class ChooseLevel : MonoBehaviour 
{ 

    string[] levelNames; 
    int i = 0; 


    public Button addIndex; 
    public Button subtractIndex; 
    public Text levelChooser; 

    string lvlName = ""; 

    void Start() 
    { 
     levelNames = PlayMenu.levelNames; 

     addIndex.onClick.AddListener(delegate() { i += 1; }); 
     subtractIndex.onClick.AddListener(delegate() { i -= 1; }); 

    } 

    void Update() 
    { 
     i = Mathf.Clamp(i, 0, levelNames.Length); 
     lvlName = levelNames[i]; 
     levelChooser.text = lvlName; 
    } 

} 

代碼附加到畫布上,這裏是現場的屏幕截圖和的一個部分檢查員在畫布:
enter image description here
enter image description here

我得到的錯誤是:

NullReferenceException: Object reference not set to an instance of an object 
ChooseLevel.Update() (at Assets/ChooseLevel.cs:28) 
+0

你有沒有創建一個'ChooseLevel'對象? – levelonehuman

+1

你永遠不應該因爲任何原因使用'SerializeField',只需標記字段「public」。就是這麼簡單。那就是如果你確定你想要這樣的行爲 – Fattie

+1

這個代碼「Mathf.Clamp(i,0 ,levelNames.Length);「是沒有意義的,你的意思可能是」i = Mathf.Clamp(i,0,levelNames.Length);「 – Fattie

回答

2

你DECL你的字符串是否在void Start()之上,但不要初始化它。 (隱式null

string lvlName; 

所以,那麼當你在Update()去的第一時間,lvlNamenull

void Update() 
{ 
    levelChooser.text = lvlName; //null the first time 
    lvlName = levelNames[i]; //THEN it's changed 
    Mathf.Clamp(i, 0, levelNames.Length); 
} 

所以根據您的遊戲邏輯則必須先分配到lvlName或一個空字符串初始化。我猜

void Update() 
{ 
    i = Mathf.Clamp(i, 0, levelNames.Length); //FIRST clamp. Thanks to Joe Blow for pointing out that it never gets reassigned. 
    lvlName = levelNames[i]; //then update lvlName 
    levelChooser.text = lvlName; //then Change the text. 
} 

應該可以正常工作。還要確保i沒有達到確切的值levelNames.Length,但我認爲這種邏輯沒問題。當您遇到越界異常時,您會注意到。

0

這只是另一個腳本中的一個小錯誤。