Generating a convex hull

Hello wonderful unity community,

I’m looking something that would generate a convex mesh with less than 255 triangles for an arbitrary high ploy concave mesh like this in Unity. The convex mesh would be used for a mesh collider.

Hi there.
So I finally found a solution.
Basically I just take 64 random polygons from the original mesh, feed those to the mesh collider and enable ‘convex’. It doesn’t have to be 64, but that’s what works for me.

using UnityEngine;
using System.Collections;

public class SimpleConvex {
	Mesh mesh;
	
	// Use this for initialization
	public SimpleConvex(Mesh mesh) {
		this.mesh = mesh;
	}
	
	public Mesh BuildSimplifiedConvexMesh()
	{
		Debug.Log(mesh.triangles.Length/3 + " tris");
		
		SplitMeshBuilder builder = new SplitMeshBuilder();
		
		for (int i = 0; i < 64; i++)
		{
			int index = Random.Range(0, mesh.triangles.Length/3) * 3;
			
			Vector3[] triangle = new Vector3[]{mesh.vertices[mesh.triangles[index]], mesh.vertices[mesh.triangles[index + 1]], mesh.vertices[mesh.triangles[index + 2]]};
			Vector2[] uvs = new Vector2[]{mesh.uv[mesh.triangles[index]], mesh.uv[mesh.triangles[index + 1]], mesh.uv[mesh.triangles[index + 2]]};
			
			builder.AddTriangleToMesh(triangle, uvs);
		}
		
		Mesh polygonSoup = builder.Build();
		Debug.Log(polygonSoup.triangles.Length/3 + " tris");
		
		return polygonSoup;
	}
}

The MeshBuilder something I made to ease mesh construction. You can make your own or I can post mine if you guys want it.

Hope it helps.

Not sure what you’re trying to do, but Unity creates such a collider automatically if you tick “Convex” in the MeshCollider.

EDIT:

As Unity (version dependently?) apparently sometimes has problems finding such a convex hull with <=255 triangles, your only other solution (except waiting for a bugfix) is to construct the convex hull yourself.

This configurable algorithm generates fast and accurate approximations for the convex hull.

For example, using “-t -n.01”, I was able to construct a 236 triangles convex hull for a 69451 triangles Stanford bunny in 3 seconds. (Note: uses Wavefront .obj, a trivial 3D file format. The only caveat: face indices start at 1, not 0).

Unity will automatically create a convex hull of the mesh when you tick ‘Convex’ in a MeshCollider.
Unity is able to create convex hulls from meshes with more than 255 triangles, but with certain kinds of meshes (i.e. highly tessellated spheres), the convex hull it generates contains more than 255 polygons. This is the reason you get error messages.

Unfortunately, Unity gives you no control over convex hull generation, so the only option is using external tools to generate a simplified mesh (or even a convex hull if you have tools which support that) with simpler shapes, and using this as the MeshCollider’s mesh.