- Home /
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.
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 $$anonymous$$anual 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:
// 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.
Thank you for the answer as well as the explanation, you made it quite easy to understand. Cheers!!
But what if there are A LOT of gameobjects in the scene. You wouldn't want to manually select all the gameobjects. Also, what if you are adding this script to a gameobject that stores children gameobjects that you also wanted to add a collider to? Is there a script that can loop through all possible child gameobjects (as well as the child's children's children's children...etc)?
Your answer
Follow this Question
Related Questions
How do I get rid of intersecting vertices between two gameobjects? 0 Answers
I need help with triggers 1 Answer
3d collider mesh to 2d collider mesh 0 Answers
Raycast starts ignoring gameobject after a few seconds 0 Answers
Prefab around a object 0 Answers