- Home /
Access gameobjects
I am trying to access the spotlight to turn Light.enabled = true or = false, how can I do that given that I have access to the gameObject Flashlight?
Answer by Hellium · May 29, 2017 at 09:28 AM
Light lightComponent = flashlightGameObject.transform.Find("Spotlight").GetComponent<Light>();
lightComponent.enabled = true ;
or
Light lightComponent = GameObject.FindWithTag("light").GetComponent<Light>();
lightComponent.enabled = true ;
If there is an other gameobject with the tag "Light", then, you may not get the "Spotlight" object
correct, but if there is only one gameobject then it is faster :P
Light lightComponent = flashlightGameObject.Find("Spotlight").GetComponent(); the flashlightGameObject should be capital I assume FlashlightGameObject, so I tried it and it says Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name ins$$anonymous$$d.
I tried the FindWithTag and it worked! I still want to figure this thing out, I am still new in unity and I would like to figure out this thing of accessing the objects hierarchically, and when to use the different options to access them Thank you
I forgot the Find
method is available on the Transform
component, not the gameobject directly. CHeck my updated answer
yes it does work but you need to change flashlightGameObject to just Flashlight which is the name of the gameObject, or was I supposed to know that already and you wrote it down to help me?? I'm confused. Thank you anyway
Answer by Jamoy1993 · May 29, 2017 at 07:09 PM
You could do
Light light = flashLightGameObject.GetComponentInChildren<Light>();
if(light != null)
{
light.enabled = true;
}
This way its only guaranteed to get a light in the children, and it will avoid null reference errors.
Your answer
![](https://koobas.hobune.stream/wayback/20220612123006im_/https://answers.unity.com/themes/thub/images/avi.jpg)