NullReferenceException: Object reference not set to an instance of an object ObjectsInformation.Start ()
Есть класc ObjectsInformation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ObjectsInformation : MonoBehaviour
{
[Header("Build Name")]
public string BuildName;
[Header("Build Information")]
public int BlockCount;
public Difficult difficult;
[Header("Updates")]
public List<Updates> levelsUpdate = new List<Updates>();
[Header("NowLevel")]
public int Level;
public enum Difficult
{
Easy,
Normal,
Hard,
Very_Hard
};
private void Start()
{
GetComponentInChildren<Text>().text = BuildName;
if (Level == 0) transform.GetChild(2).GetComponent<Text>().text = "Построить";
else transform.GetChild(2).GetComponent<Text>().text = "Улучшить";
}
}
класс Update из которых состоит лист в ObjectsInformation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public class Updates
{
public int level;
public Image Image;
public GameObject Object;
}
Выдает NullReferenceException: Object reference not set to an instance of an object ObjectsInformation.Start () в
if (Level == 0) transform.GetChild(2).GetComponent<Text>().text = "Построить";
else transform.GetChild(2).GetComponent<Text>().text = "Улучшить";
Объясните в чем проблема пожалуйста...
Ответы (2 шт):
У объекта к которому вы обращаетесь (transform.GetChild(2)) не существует компонента типа <Text>.
Убедитесь, что вы обращаетесь именно к тому объекту, выведя в консоль его имя:
Debug.Log(transform.GetChild(2).ToString());
Убедитесь, что у этого объекта есть компонент Text.
PS: возможно, стоит обратить внимание на поиск объекта по тегу. Это будет более надежно, и не сильно повлияет на производительность, если произвести такую операцию в методе Start и потом обращаться к нему через сохраненную ссылку.
NullReferenceException: то к чему вы обращаетесь не существует.
Компонент Text в вашем случае.
if (transform.childCount >= 2) {
Text BtnText = transform.GetChild(2).GetComponent<Text>();
if (BtnText != null)
BtnText.text = Level == 0 ? "Построить" : "Улучшить";
}
ObjectsInformation нету нужды быть MonoBehaviour. Лучше ScriptableObject.
То что у вас происходит в Start вообще не имеет дело к ObjectsInformation, это должен быть отдельный MonoBehaviour с полями ссылок на объекты Text, без всяких GetChild;