- Home /
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?
Answer by vogles · Jul 17, 2015 at 06:13 PM
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.
Answer by Dave-Carlile · Jul 17, 2015 at 06:16 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220611231748im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why we have to use getcomponent instead of a simple reference ? 2 Answers
How to update UI image mid-game (Unity, C#) 2 Answers
Meaning of .text 1 Answer