I want to add colliders to the children of a gameObject.
Here’s what I have but it is not working.
foreach (Transform childObject in transform)
{
Mesh mesh = childObject.gameObject.GetComponent<MeshFilter>().mesh;
MeshCollider meshCollider = childObject.gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
meshCollider.convex = true;
meshCollider.sharedMesh = mesh;
}
Don’t know what this isn’t working.
I am getting this error.
MissingComponentException: There is no 'MeshFilter' attached to the "RootNode" game object, but a script is trying to access it.
Neriad
November 21, 2019, 10:05am
2
If you use GetComponentsInChildren() to fill in childObject it also gets the transform of the parent, so if it has no MeshFilter attached you get the error on the Getcomponent request.
If you are not using GetComponentsInChildren(), just check the objects that are inside childObject and you will see one of them won’t have a MeshFilter component attached on it. And the object seems to be “RootNode”.
I need to add mesh filters to all the children as well.
How do I approach that?
I have all the names using this
foreach (Transform g in transform.GetComponentsInChildren<Transform>())
{
Debug.Log(g.name);
}
I was able to do it with this.
foreach (Transform g in transform.GetComponentsInChildren<Transform>())
{
Debug.Log(g.name);
Mesh mesh = g.gameObject.AddComponent<MeshFilter>().mesh;
MeshCollider meshCollider = g.gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
}
Is this the right way to do it?
But I need them to be “convex” and this doesn’t work.
foreach (Transform g in transform.GetComponentsInChildren<Transform>())
{
Debug.Log(g.name);
Mesh mesh = g.gameObject.AddComponent<MeshFilter>().mesh;
MeshCollider meshCollider = g.gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
meshCollider.convex = true;
}
What am I missing?
EDIT: It did work…I didn’t save my code.