- Home /
Finding a specific layer's MeshRenderer
I have the following method (originally found here), which searches through all layers with a specific name in order to then find its associated MeshRenderer
:
Renderer FindGameObjectsWithLayer (string layerName)
{
Renderer renderer = null;
GameObject[] goArray = FindObjectsOfType (typeof(GameObject)) as GameObject[];
for (int i = 0; i < goArray.Length; i++) {
var layer = goArray [i];
if (layer.gameObject.layer == LayerMask.NameToLayer (layerName)) {
renderer = layer.gameObject.GetComponent<MeshRenderer> ();
break;
}
}
return renderer;
}
My question is whether there's an easier way to simply find a layer with a name and then use GetComponent()
to find its associated MeshRenderer
or gameObject component?
UPDATE:
I find that I can also use the following method, but I'm still after a more efficient way of doing this:
Renderer FindMeshRenderer (string tag)
{
try {
return GameObject.FindGameObjectsWithTag (tag) [0].GetComponent<MeshRenderer> ();
} catch (UnityException ex) {
Debug.Log (ex.Message);
return null;
}
}
I'm aware that doing this inside Update()
isn't recommended so I'm simply caching this in a Start()
event only.
Your answer
Follow this Question
Related Questions
How to fill the inside volume of a 3D mesh with color? 0 Answers
how to access a float from one script in other script in different objects 3 Answers
performance between disable renderer and disable gameObject 2 Answers
Turning off renderer in other game object (C#) 2 Answers
How to run a function in a GO that have DontDestroyOnLoad 1 Answer