首先,我知道有一个与此类似的主题,即: Can't find the reason for this NullReferenceException
代码如下:
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
[System.Serializable]
public class SaveLoadMenuButtons : MonoBehaviour
{
[SerializeField]
private Transform[] transforms;
[SerializeField]
public MenuType currentMenu;
[SerializeField]
private static bool logProgress = false;
[SerializeField]
private List<string> textos;
[SerializeField]
private string gameName = "Your Game";
[SerializeField]
private float menuIndex;
[SerializeField]
private int maxIndex;
[SerializeField]
private int numButtons;
public void Start()
{
showMenu = false;
textos = new List<string>();
GuardarCargarBotones.SetActive(false);
menuIndex = 0;
firstTime = true;
hasPressedDirectionalPad = false;
selectItem = false;
numButtons = GuardarCargarBotones.transform.childCount;
transforms = new Transform[numButtons];
for (int i = 0; i < numButtons; ++i)
{
transforms[i] = GuardarCargarBotones.transform.GetChild(i);
}
textos.Add("Volver");
textos.Add("Guardar Visita");
foreach (LevelSerializer.SaveEntry sg in LevelSerializer.SavedGames[LevelSerializer.PlayerName])
{
textos.Add(sg.Caption);
}
for (int i = 2; i < numButtons; i++)
{
if (textos[(int)menuIndex] != null)
{
transforms[i].GetComponentInChildren<UnityEngine.UI.Text>().text = textos[(int)menuIndex];
if ((i < numButtons - 1) && (menuIndex < textos.Count - 1)) menuIndex++;
}
}
maxIndex = textos.Count;
}
Unity表示问题在于:
transforms[i].GetComponentInChildren<UnityEngine.UI.Text>().text = textos[(int)menuIndex];
。
错误是:
NullReferenceException:未将对象引用设置为对象的实例
经过一些测试,我发现问题出在函数transforms[i].GetComponentInChildren<UnityEngine.UI.Text>().text
之前我遇到过这个错误,通常是由于缺少对象的初始化,但这次我已经初始化了列表。什么是问题的任何想法?我真的找不到它。
谢谢。