I’m trying to turn off all my renderers on my object, and all their child’s. So what I’m doing is getting all the components in the gameObect in a for loop and using a renderer.enabled = false. But sometimes the game object might not have an renderer, and it will throw an error.
How would I do an if statement to check firstly if it has a renderer, then shut it off:
var components = GetComponents(Component);
for(var c : Component in components){
if(Renderer)
c.renderer.enabled = false;
}
It doesn’t really make sense to get all of the components, if you’re just looking for renderers – a renderer is a component.
You could do something like this:
for ( var r : Renderer in GetComponents(Renderer) )
{
r.enabled = false;
}
This can potentially cause a compiler warning about implicit downcasts, which you can avoid by adding #pragma downcast to your script, or treating r as a Component which you always cast to a Renderer.
If you want to search an entire GameObject and its children, you could use GetComponentsInChildren() instead.