Accessing children of an instance doesn't work every time

Hey,

I don’t get the problem with the following code:

using UnityEngine;
using System.Collections;

public class brain1 : MonoBehaviour {
 
 public GameObject level;
 public GameObject cube;
 
 public int i = 1;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 if(Input.GetKeyDown (KeyCode.U))
 {
 if(level)
 Destroy(level);
 
 level = Instantiate (Resources.Load ("container"+i)) as GameObject;
 i++;
 
 cube = GameObject.Find("army");
 }
 
 Debug.Log (cube.transform.childCount);
 }
}

container1 is a prefab (empty gameobject) in “Resources” with an empty gameobject in it which is called “army” and has 1 cube in it.

container2 is the same thing with 2 cubes in “army”.
container3 still the same with 3 cubes in “army”.

now I want get the number of children from the Debug function when I press U.

When I press it the first time it works and I get the msg “1”.

When I press it the scond time I get the error:

MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it. Your script should either check if it is null or you hould not destroy the object. brain1.Update () (at Assets/Standard Assets/Scripts Test/brain1.cs:30)

When I press it the third time, I get “3”

wtf?

So that means, that someone there is no gameobject level.
But it appears on the scene!

How can I access the gameobject level correctly?

I tried a lot of stuff and did a lot of research today and the last day for hours but I can’t get what is wrong.
Please help!

Destroy does not destroy immediately but at the end of the frame. So it is possible that GameObject.Find finds the destroyed cube because it is still there.

The best solution would be to avoid GameObject.Find, and to iterate through the children of the new instantiated prefab to get the cube.

Something like:

level = Instantiate (Resources.Load ("container"+i)) as GameObject;
i++;

foreach(Transform child in level.transform)
{
    if(child.gameObject.name == "army")
    {
        cube = child.gameObject;
        break;
    }
}

Anyway, after you call Destroy it is safer to set all references to null:

if(level)
    Destroy(level);
level = null;
cube = null;