Null Reference Error when accessing a child's script component immediately after adding it?


In a game with 3 floors, and each floor has a list of 2 or 3 objectives to be completed before moving on, I’m trying to make something like a checklist in the UI where each floor has a header, and under each header is an objective that the player needs to complete, or has completed. It looks something like this:

  • (Checklist Panel Parent)
  • Floor child 1Header
  • Objective sub-child 1 text
  • Objective sub-child 2 text
  • Objective sub-child 3 text
  • Floor child 2 Header
  • And so on…

The Checklist Panel has a script that keeps track of how many Floors it has. When the game starts, a foreach loop goes through each of the Checklist Panel’s floors and adds them to a list.

But during a Floor’s iteration, a script is added as a component to keep track of a Floor’s sub-children, and another foreach loop is run to add the sub-children. But when the loop tries to add the sub-children, a NullReferenceException is thrown even though I thought I did it correctly. What did I do wrong?

The Checklist Panel Script:

	private static ChecklistPanel instance;

	public static ChecklistPanel Instance
			if (instance == null)
				instance = GameObject.FindObjectOfType<ChecklistPanel> ();

			return instance;

public List<GameObject> floorChildren;	//Hold each floor in the checklist panel.

	void Start()
		//Reinitialize the lists when returning to the main scene.

		foreach (Transform floor in ChecklistPanel.Instance.transform) 
			//Get all the Floors under the Checklist Panel and add the ChecklistFloorChildren Script.
			floorChildren.Add (floor.gameObject);
			floor.gameObject.AddComponent <ChecklistFloorChildren>();

			//Then, cycle through the current Floor's Objectives (its children), and add each child to the Floor's list
			//of Objecives.
			foreach (Transform objective in floor.transform) 
				floor.gameObject.GetComponent<ChecklistFloorChildren> ().objectiveChildren.Add (objective.gameObject);

The script added to each Floor:

	//Hold's each floor's list of objectives. A list will be called from the ChecklistPanel script to add
	//each floor's child into a list.

	public List<GameObject> objectiveChildren;

I apologize for the code’s formatting. I don’t often post questions here, and I’m having trouble keeping the formatting the same, but I hope this makes sense. Thank you.

objectiveChildren is null in ChecklistFloorChildren.

public List<GameObject> objectiveChildren = new List<GameObject>();

The list needs to be created when the component is added. If ChecklistFloorChildren is added to a GameObject in the Editor, then Unity will create the list for us so it can be used in the inspector.