- Home /
Collision on generated mesh
According to the documents, mesh colliders are only constructed when the mesh is placed into the scene.
Is it possible to force a collider component to construct itself based on a mesh filter which you yourself have constructed at runtime? i.e. if geometry changes?
I.e. if I were to make a parametric spiral mesh, for example, and wanted to be able to tweak how many degrees it generates through at run time, and then wanted the result to be collidable, how would I go about that?
If a prefab was instantiated into the scene, and the geometry was constructed in the "Start()" function, would that be early enough to let the mesh collider construct itself?
Or should I add a mesh collider to the game object at runtime after the mesh data is set up?
Answer by duck · Oct 21, 2010 at 11:26 AM
All you need to do is add the mesh collider component to the same object after you've finished generating the procedural mesh itself. It's fine if it's all in the Start() method. For example:
void Start() {
// create new Mesh Filter & Mesh objects
var meshFilter = AddComponent<MeshFilter>();
var mesh = new Mesh();
// set up mesh
mesh.name = name;
mesh.vertices = myVerts;
mesh.triangles = myTris;
mesh.RecalculateNormals();
meshFilter.mesh = mesh;
mesh.RecalculateBounds();
// add collider!
AddComponent<MeshCollider>();
}
Thank you!
There's no need to point the $$anonymous$$eshCollider at the actual mesh, after adding it, or...?
No, I guess unless you specifically tell it to use another mesh, it uses the same mesh as the $$anonymous$$eshFilter object.
If you want to make a lower-res proxy mesh for the collision (while using a higher res mesh for the renderer), you'd have to look into that more closely - or just use separate gameObjects for each :)
Your answer
Follow this Question
Related Questions
minimize vertex artifacting for procedural mesh manipulations - vertex collision same object? 0 Answers
Procedural Geometry doesn't collide.. 1 Answer
Best approach for collision in shape combination game? 0 Answers
Having an array of points(vector2), how do I create a 2d terrain? (new to unity) 2 Answers
Combine common surfaces 1 Answer