- Home /
 
 
               Question by 
               dankorotin · Apr 13, 2018 at 09:17 PM · 
                materialmaterialsrenderermesh renderer  
              
 
              How to check whether a lot of components and their children have a mesh renderer on them in code?
Hello!
I'm trying to get a piece of code to activate only if the game object has a mesh renderer on it. Can someone please help me with this? The only answer I found was from 2012 and doesn't seem to work anymore.
Best, Danylo
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by MarioSantoso · Apr 13, 2018 at 11:37 PM
If you want to check a gameobject and all its children and grandchildren, you must do a recursive check
Fire this up and you should good to go
 using UnityEngine;
 
 public class Test : MonoBehaviour
 {
     private void Start()
     {
         Debug.Log(DoIHaveMeshRenderer(transform));
     }
 
     public bool DoIHaveMeshRenderer(Transform objectToBeChecked)
     {
         bool _descendantHasMeshRenderer = false;
         if (objectToBeChecked.childCount > 0)
             for (int i = 0; i < objectToBeChecked.childCount; i++)
                 _descendantHasMeshRenderer = DoIHaveMeshRenderer(objectToBeChecked.GetChild(i));
 
         if (_descendantHasMeshRenderer)
             return true;
 
         if (objectToBeChecked.GetComponent<MeshRenderer>() != null)
             return true;
         else
             return false;
     }
 }
 
              Your answer
 
             Follow this Question
Related Questions
How do I change the material of a prefab when it is not in the hierarchy? 0 Answers
Swapping out a single material on a SkinnedMeshRenderer at runtime 0 Answers
Renderer.material assignment not working 1 Answer
Changing two different objects renderer colour 1 Answer
How to compare 2 materials? 2 Answers