- Home /
Creating a working meshcollider in code
I want to do raycasts on a mesh, now it appears that raycasts only hit front facing triangles, but I want it to hit both back and front facing triangles.
Unfortunately this doesn't seem to be optional, so instead I make a new mesh, copy all vertices and triangles, and add all triangles again in reversed order. And then assign this new mesh to the collider.
Now here's the problem, when I do this, every and any raycast results false.
Unless, I first make the collider and keep it in the scene, then select it and change some values (and set these back to how they where before), and then do the raycasts, and then it suddenly does work.
So what's wrong? (and how do I fix it?) It's as if something needs to happen to a new mesh before it can be used, something that happens automatically, but not immediately it seems.
Answer by Steven-1 · Apr 12, 2013 at 10:15 AM
Found the answer here: http://answers.unity3d.com/questions/14465/how-to-assign-procedural-mesh-to-a-collider.html and here: http://answers.unity3d.com/questions/171571/dynamic-mesh-collider.html
It appears it works if you first create the mesh and then assign it to the collider, rather than assigning a new empty mesh, and then setting the vertices and triangles (which was what I actually did). Otherwise it also works, but only after 1 frame or so.
Answer by OP_toss · Apr 11, 2013 at 10:52 PM
Ew don't do that. 2 overlapping colliders in the same mesh?!
Instead make 2 colliders, one with front-faces, one with back-faces. Unless of course there's some way to switch off backfacing for collision meshes that I don't know about...
the collider is only used for raycasts, so I doubt this has any disadvantage over having 2 colliders. Regardless, that's not the issue, if I make a new mesh that's just the exact same mesh as the original, the problem is still there
Answer by Hyarch · Feb 27, 2015 at 07:30 AM
All Wrong Your Probably Assigning The Mesh Colliders to a Parent of a Mesh Object or fbx
if 2 overlapping colliders Ignore Layer in settings
foreach(Transform child in modelobj.transform){
MeshCollider ObjCollider = child.transform.gameObject.AddComponent("MeshCollider") as MeshCollider;
}