- Home /
Check If GameObject Has Render Component
Hi,
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;
}
Answer by rutter · May 24, 2012 at 12:30 AM
You're close.
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.
Answer by aldonaletto · May 24, 2012 at 12:40 AM
In Unity, testing the reference to a component or game object returns true when the component exists, and false if not:
var components = GetComponents(Component); for(var c : Component in components){ if(c.renderer) c.renderer.enabled = false; }
Your answer
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
How much do I need to optimize off-screen objects? 2 Answers
Trail Renderer detection 0 Answers
Setting Textures causes GameObject Material to turn black? 1 Answer
there is no renderer attached to the "player" game object, but script is trying to access it. 0 Answers