- Home /
Problems with finding all children that have meshes
I am looking for all objects in a hierarchy that have meshes. This includes the object itself and any of its children. The purpose is to attach a mesh effect.
If I use:
var mesh : MeshFilter = gameObject.GetComponentInChildren(MeshFilter);
mesh.gameObject.AddComponent ("MeshExplode");
It finds the first mesh and works fine. But as I want to have all meshes I am trying the following:
var meshes : MeshFilter[] = gameObject.GetComponentsInChildren(MeshFilter) as MeshFilter[];
if(meshes)
{
for (var mesh : MeshFilter in meshes)
{
Debug.Log("Found mesh =======================================");
mesh.gameObject.AddComponent ("MeshExplode");
}
}
else
{
Debug.Log("No meshes");
}
This doesnt find any meshes and I am completely confused to why.
Answer by Fabkins · Nov 06, 2011 at 02:06 PM
Ok, I've found my own answer. I put the result of the find straight into the for loop. I have no idea why it didnt work when the result in an array but the following works a treat:
for (var mesh : MeshFilter in gameObject.GetComponentsInChildren(MeshFilter) )
{
Debug.Log("Found mesh =======================================");
mesh.gameObject.AddComponent ("MeshExplode");
}
Answer by syclamoth · Nov 06, 2011 at 01:20 PM
Is it even getting to the for loop? It's possible that you can't cast a MeshFilter[] to a boolean, and so
if(meshes)
always returns false! Try
if(meshes.Length > 0)
instead, see if that works any better.
That gets me:
NullReferenceException: Object reference not set to an instance of an object
Its driving me buggy.....
In theory I shouldnt even need the if condition statement, I ought to be able to drop straight into the loop but produces the same as the above error....
(worth a try though)
Well, that means that meshes isn't getting assigned properly! Is all of this happening inside a function? I'm afraid I can't really help you much more here, I'm not that good at JavaScript (I could help you if it were C# though)
Hi syclamoth, yes its happening in a function. The bit I just dont understand is why getting the first instance works but getting an array of all of them doesnt.
Thanks for your suggestions anyhow.
Your answer
![](https://koobas.hobune.stream/wayback/20220613033507im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I retrieve deep levels of nested child transforms with a generic snippet of code 2 Answers
How do I access Mesh/ Meshfilter in Editor code? 3 Answers
GetComponentInChildren is getting Sibling s Child 0 Answers
WHy cant I create the GetComponentsInChildren(Renderer) array? 2 Answers
How to get script from Object with (Clone)'s script? 2 Answers