我正在嘗試做一個關卡選擇菜單。這是我的佈局的截圖:爲了使這項工作,這是我促成這件事情的腳本: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;
}
}
代碼附加到畫布上,這裏是現場的屏幕截圖和的一個部分檢查員在畫布:
我得到的錯誤是:
NullReferenceException: Object reference not set to an instance of an object
ChooseLevel.Update() (at Assets/ChooseLevel.cs:28)
你有沒有創建一個'ChooseLevel'對象? – levelonehuman
你永遠不應該因爲任何原因使用'SerializeField',只需標記字段「public」。就是這麼簡單。那就是如果你確定你想要這樣的行爲 – Fattie
這個代碼「Mathf.Clamp(i,0 ,levelNames.Length);「是沒有意義的,你的意思可能是」i = Mathf.Clamp(i,0,levelNames.Length);「 – Fattie