How to reference an inactive GameObject?

I’m trying to access an inactive gameobject that is the child of another gameobject, but I’m having trouble.

Right now I’m using this line of code to try to access the inactive child gameobject and set it active:

go.GetComponentInChildren<EnemyMover>().gameObject.SetActive(true);

I am getting a null ref error.

So how can I reference an inactive gameobject?

I’m not sure if there’s a more efficient way of doing it, but you should try getting the reference before it goes inactive.

  1. Add a “public GameObject inactiveGOYouWant” to your script. Then in the Inspector, add the reference. (This feels hacky to me, but it should work)

  2. Perhaps a slightly cleaner approach could be to do #1, but on a script on the parent of the inactive child. Then other scripts can simply do “go.GetComponent().inactiveGOYouWant.SetActive(true)”.

  3. Similar to #2, but instead of using the Inspector, have the parent object get a reference to the child in Awake.

You’ll need to keep a reference to the object.

Or you can run through all the children yourself using Transform.childCount and Transform.GetChild, and use GetComponent on each child to see if it has the component.