Created
March 30, 2016 00:44
-
-
Save marcelschmidtdev/6e3bfb49c8b5b7a65ef94b6dea136ab5 to your computer and use it in GitHub Desktop.
Gets all bounding boxes and returns a new one which encapsulate them all (Unity)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class RecursiveBoundingBox | |
{ | |
//Gets all bounding boxes and returns a new one which encapsulate them all | |
//This is e.g. useful if you want to calculate the actual size of a gameobject | |
//Using "MeshRenderer" means it uses the data from "MeshFilter" applied to "Transform" | |
public static Bounds RecursiveMeshRendererBoundingBox (GameObject go) | |
{ | |
MeshRenderer[] meshRenderers = go.GetComponentsInChildren<MeshRenderer>(); | |
if (meshRenderers.Length > 0) | |
{ | |
Bounds b = meshRenderers[0].bounds; | |
for (int i = 1; i < meshRenderers.Length; i++) | |
{ | |
b.Encapsulate(meshRenderers[i].bounds); | |
} | |
return b; | |
} | |
else | |
{ | |
return new Bounds(); | |
} | |
} | |
//Using "MeshFilter" means it uses the raw mesh data without applied position of "Transform" | |
public static Bounds RecursiveMeshFilterBoundingBox (GameObject go) | |
{ | |
MeshFilter[] meshFilters = go.GetComponentsInChildren<MeshFilter>(); | |
if (meshFilters.Length > 0) | |
{ | |
Bounds b = meshFilters[0].mesh.bounds; | |
for (int i = 1; i < meshFilters.Length; i++) | |
{ | |
b.Encapsulate(meshFilters[i].mesh.bounds); | |
} | |
return b; | |
} | |
else | |
{ | |
return new Bounds(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment