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.
Sure... Either write an Editor Extension for an existing script or create a script for an Editor Window. Examples for both solutions are available on the User Manual and Scripting API. The solution would load all meshes into an array with Resources.LoadAll, and then iterate through the body parts or whatever and assign meshes with the same name.
Answer by Bunny83
Apr 22, 2016 at 11:44 PM
A quick and dirty solution would be a script like this:
public class AddMeshCollider : MonoBehaviour
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.
Thank you for the answer as well as the explanation, you made it quite easy to understand. Cheers!!
Thank you this saved me a lot of time!
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
64 People are following this question.
How do I get rid of intersecting vertices between two gameobjects?
How Can I switch between 2 colliders in my 2D Game?
Game Object not activating when commanded by function in another script.
Workaround to Non-Convex mesh colliders with non-Kinematic RigidBodies?
c#: Best practice to toggle visiblity of meshes within a gameObject?