- Home /
How do I add MeshCollider to a cow correctly through scripting?
How do you add a Mesh Collider to a GameObject.
I add one but in the inspector it has no mesh attached to the inspector mesh item. How do you do that through the script?
moo=GameObject.Find("cow"); moo.AddComponent(MeshCollider); now how do I attach the mesh..
The cow fbx model has this structure
cow--> LMBullAnimations, LMBull Mesh
So I'm not sure if these means that the LMBull is a submesh or the original mesh. Anyway all I want to do is add the meshcollider succesfully through a script.
Thanks,
Dan
Answer by Mike 3 · May 12, 2010 at 10:36 AM
when you do AddComponent, it gives you back a reference to the MeshCollider
so you could do something like this:
var mooCollider : MeshCollider = moo.AddComponent(MeshCollider);
mooCollider.sharedMesh = yourMesh;
where yourMesh is a reference to the mesh in question - you could probably get it from the MeshFilter on the cow
Answer by HarvesteR · Apr 05, 2011 at 10:00 PM
You can even cut that into a one-liner:
moo.AddComponent(MeshCollider).sharedMesh = yourMesh;
This will give it a meshcollider and assign the mesh, all in one go.
Mind that when you give an object a meshcollider, it will automatically try to use the object's own mesh... That might be what you want or it might not.
Also, keep in mind that to change a mesh collider's mesh after it already has one, you have to first set it to null, then assign the new mesh.
//replacing mesh in meshcollider
GetComponent(MeshCollider).sharedMesh = null;
GetComponent(MeshCollider).sharedMesh = newMesh;
Cheers