Question by
manuelmangual · Jan 27, 2017 at 07:52 PM ·
c#unity 5instantiate
Issues instantiating a game object
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[i].Title;
_objectiveListInstance.transform.Find("Counter").GetComponent<Text>().text = stats.MyObjectives[i].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[i].Active)
{
_objectiveListInstance.transform.Find("Counter").GetComponent<Text>().color = Color.yellow;
_objectiveListInstance.transform.Find("ObjectiveText").GetComponent<Text>().color = Color.yellow;
}
else
{
_objectiveListInstance.transform.Find("ObjectiveText").GetComponent<Text>().color = Color.white;
_objectiveListInstance.transform.Find("Counter").GetComponent<Text>().color = Color.white;
}
if (stats.MyObjectives[i].Active)
{
_objectiveListInstance.transform.Find("Counter").GetComponent<Text>().color = Color.yellow;
_objectiveListInstance.transform.Find("ObjectiveText").GetComponent<Text>().color = Color.yellow;
}
else
{
_objectiveListInstance.transform.Find("ObjectiveText").GetComponent<Text>().color = Color.white;
_objectiveListInstance.transform.Find("Counter").GetComponent<Text>().color = Color.white;
}
if (stats.MyObjectives[i].Completed)
{
_objectiveListInstance.transform.Find("Toggle").GetComponent<Toggle>().isOn = true;
_objectiveListInstance.transform.Find("ObjectiveText").GetComponent<Text>().color = Color.gray;
_objectiveListInstance.transform.Find("Counter").GetComponent<Text>().color = Color.gray;
}
else
{
_objectiveListInstance.transform.Find("Toggle").GetComponent<Toggle>().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!
Comment
Best Answer
Answer by EDevJogos · Jan 27, 2017 at 07:57 PM
You're assining your _objectiveListInstance at the Start(); but OnEnable is called before that:
https://docs.unity3d.com/Manual/ExecutionOrder.html
OnEnable will be called again if you Active and Deactive your object, but if he starts active OnEnable() will be before the Start();