Hello, I am instantiating a list of UI game objects. But when I start the game I get a
null reference exception: object
reference not set to an instance of an
object
Here is my code:
public class MyClass: Monobehaviour
{
public GameObject ObjectiveTextPrefab;
private GameObject _objectiveListInstance;
void Start()
{
_data = GameData.Instance.LoadData();
var stats = _data.Scenarios.FirstOrDefault(t => t.Name == Scenario.ToString());
for (int i = 0; i < stats.MyObjectives.Length; i++)
{
_objectiveListInstance = Instantiate(ObjectiveTextPrefab);
_objectiveListInstance.transform.SetParent(objectivesListParent, false);
_objectiveListInstance.transform.Find("ObjectiveText").GetComponent<Text>().text = stats.MyObjectives*.Title;*
_objectiveListInstance.transform.Find(“Counter”).GetComponent().text = stats.MyObjectives*.Count.ToString();*
}
}
void OnEnable()
{
_data = GameData.Instance.LoadData();
var stats = _data.Scenarios.FirstOrDefault(t => t.Name == Scenario.ToString());
for (int i = 0; i < stats.MyObjectives.Length; i++)
{
if (stats.MyObjectives*.Active)*
{
_objectiveListInstance.transform.Find(“Counter”).GetComponent().color = Color.yellow;
_objectiveListInstance.transform.Find(“ObjectiveText”).GetComponent().color = Color.yellow;
}
else
{
_objectiveListInstance.transform.Find(“ObjectiveText”).GetComponent().color = Color.white;
_objectiveListInstance.transform.Find(“Counter”).GetComponent().color = Color.white;
}
if (stats.MyObjectives*.Active)*
{
_objectiveListInstance.transform.Find(“Counter”).GetComponent().color = Color.yellow;
_objectiveListInstance.transform.Find(“ObjectiveText”).GetComponent().color = Color.yellow;
}
else
{
_objectiveListInstance.transform.Find(“ObjectiveText”).GetComponent().color = Color.white;
_objectiveListInstance.transform.Find(“Counter”).GetComponent().color = Color.white;
}
if (stats.MyObjectives*.Completed)*
{
_objectiveListInstance.transform.Find(“Toggle”).GetComponent().isOn = true;
_objectiveListInstance.transform.Find(“ObjectiveText”).GetComponent().color = Color.gray;
_objectiveListInstance.transform.Find(“Counter”).GetComponent().color = Color.gray;
}
else
{
_objectiveListInstance.transform.Find(“Toggle”).GetComponent().isOn = false;
}
}
}
}
The error points to the _objectiveListInstance variable found in the OnEnable() function. It says that it is null. Can someone help me understand why I am getting this issue? Many thanks in advance!