- Home /
Duplicate: http://answers.unity3d.com/questions/1413638/how-to-find-gameobject-child.html
How can I find gameObject child.
So I made a gameObject named camera then I dragged the main camera into the camera gameObject. So then In my code, I wanted to disable the script attached to the main camera named Camera Shaker, so I used this:
GameObject.Find("MainCamera").GetComponent<CameraShaker>().enabled = false;
I made a question like this one but the people in the question didn't know how to do this. Then someone suggested I use this instead:
GameObject.Find("MainCamera").GetComponentInChildren<CameraShaker>().enabled = false;
This didn't work.
BY THE WAY I'M SCRIPTING THIS IN A DIFFERENT SCRIPT AND ALSO A DIFFERENT GAMEOBJECT.
Here's why I can't just use this line of code GameObject.Find("MainCamera").GetComponentInChildren().enabled = false; This line of code, GameObject.Find("").GetComponent<>(); can access children of gameObjects, but only when this script is attached to the parent of the child you are trying to access. For example, the Player gameObject has a child named 'Gun'. This Gun gameObject which is the child of the Player gameObject has a script named 'Bullet_Spawner'. Now I want to disable the Bullet_Spawner script in the Start Method/Function, so I use this line of code:
GameObject.Find("MainCamera").GetComponent().enabled = false;
And it works.