Assign a Mesh to Mesh Collider Automatically

I am making an Anatomy App and I am in the process of assigning mesh colliders to each bone and muscle so that they are clickable. Is there a way to assign the mesh automatically to The Collider so that I don’t have to individually select the correct mesh for each Collider.

A quick and dirty solution would be a script like this:

// AddMeshCollider.cs
using UnityEngine;

public class AddMeshCollider : MonoBehaviour
{
    void Reset()
    {
        Mesh m = null;
        var mf = GetComponent<MeshFilter>();
        if (mf != null)
            m = mf.sharedMesh;
        var smr = GetComponent<SkinnedMeshRenderer>();
        if (smr != null)
            m = smr.sharedMesh;
        if (m != null)
        {
            var col = GetComponent<MeshCollider>();
            if (col == null)
                col = gameObject.AddComponent<MeshCollider>();
            col.sharedMesh = m;
        }
    }
}

This script, when added to a gameobject in the editor, should automatically:

  • Search for MeshFilter / SkinnedMeshRenderer components on the gameobject the script is attached to and if one is found it will copy the mesh reference.
  • ensure that a MeshCollider is attached to the gameobject if there’s either a MeshFilter or SkinnedMeshRenderer attached and it will assign the mesh it has found in step 1.

Reset should be called automatically when you add the script to a gameobject. Once added you can also use the context menu of the script component and select “Reset” to run the method once more.

The script has no function at runtime so once you have added it, you could remove it immediately. Keep in mind that you can select multiple objects and drag the script onto the inspector to add that component to all objects at once. Same for removing it.