So I’ve got an Indicator on a car, which has a light atached to it.
Now, when I try to access that light in a script, via
GameObject.Find("IndicatorLightR").GetComponent<Light>().enabled = false;
I get a MissingComponentException, which tells me, theres no ‘Light’ attached to the “IndicatorLightR”, although there clearly is one.
Also, when looking at the Inspector, it tells me that the script found “IndicatorLightR (Preview Scene)” instead of just “IndicatorLightR”
Whats going on?
I think you might have multiple objects called “IndicatorLightR” in your scene. GameObject.Find() only returns the first one it finds. If by the time it gets called there are multiple objects with the same name, it may return one that doesn’t have the component you’re looking for.
GameObject.Find() isn’t usually a method that you want to use outside of a quick prototyping context. Instead, I’d recommend using Tags, or a direct reference to the GameObject. Also, make sure your GameObject is enabled when you try to find it.
Another debug process would be to break up your line into several:
GameObject target = GameObject.Find("IndicatorLightR");
Light targetComponent = target.GetComponent<Light>();
if(targetComponent != null)
targetComponent.enabled = false;
This gives you the ID of the component, that you can then compare to its id in the Inspector (in Debug mode. Right click the inspector and set it to “Debug” instead of “Normal”). That way you can make sure it’s the object you want.
Hope that helps!