Skip to content

Instantly share code, notes, and snippets.

@danielbierwirth
Last active July 18, 2017 14:56
Show Gist options
  • Save danielbierwirth/4704573841072d4646f950685fb86c04 to your computer and use it in GitHub Desktop.
Save danielbierwirth/4704573841072d4646f950685fb86c04 to your computer and use it in GitHub Desktop.
unity function that gets all meshes of parent gameObject including it's child gameObjects and adds corresponding meshcollider to parent gameObject
/// <summary>
/// Add mesh collider to game object
/// Gets all child components, looks for meshes and assings
/// them to gameobject meshcollider
/// </summary>
/// <param name="containerModel">The gameobject</param>
private void AddMeshCollider (GameObject containerModel)
{
// Add mesh collider
MeshFilter meshFilter = containerModel.GetComponent<MeshFilter>();
if (meshFilter != null)
{
MeshCollider meshCollider = containerModel.AddComponent<MeshCollider>();
meshCollider.sharedMesh = meshFilter.sharedMesh;
}
// Add mesh collider (convex) for each mesh in child elements.
Component[] meshes = containerModel.GetComponentsInChildren<MeshFilter>();
foreach (MeshFilter mesh in meshes)
{
MeshCollider meshCollider = containerModel.AddComponent<MeshCollider>();
meshCollider.sharedMesh = mesh.sharedMesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment