using UnityEngine; using System.Collections; namespace MoreMountains.Tools { /// /// Bounds helpers /// public class MMBoundsExtensions : MonoBehaviour { /// /// Returns a random point within the bounds set as parameter /// /// /// public static Vector3 MMRandomPointInBounds(Bounds bounds) { return new Vector3( Random.Range(bounds.min.x, bounds.max.x), Random.Range(bounds.min.y, bounds.max.y), Random.Range(bounds.min.z, bounds.max.z) ); } /// /// Gets collider bounds for an object (from Collider2D) /// /// /// public static Bounds GetColliderBounds(GameObject theObject) { Bounds returnBounds; // if the object has a collider at root level, we base our calculations on that if (theObject.GetComponent()!=null) { returnBounds = theObject.GetComponent().bounds; return returnBounds; } // if the object has a collider2D at root level, we base our calculations on that if (theObject.GetComponent()!=null) { returnBounds = theObject.GetComponent().bounds; return returnBounds; } // if the object contains at least one Collider we'll add all its children's Colliders bounds if (theObject.GetComponentInChildren()!=null) { Bounds totalBounds = theObject.GetComponentInChildren().bounds; Collider[] colliders = theObject.GetComponentsInChildren(); foreach (Collider col in colliders) { totalBounds.Encapsulate(col.bounds); } returnBounds = totalBounds; return returnBounds; } // if the object contains at least one Collider2D we'll add all its children's Collider2Ds bounds if (theObject.GetComponentInChildren()!=null) { Bounds totalBounds = theObject.GetComponentInChildren().bounds; Collider2D[] colliders = theObject.GetComponentsInChildren(); foreach (Collider2D col in colliders) { totalBounds.Encapsulate(col.bounds); } returnBounds = totalBounds; return returnBounds; } returnBounds = new Bounds(Vector3.zero, Vector3.zero); return returnBounds; } /// /// Gets bounds of a renderer /// /// /// public static Bounds GetRendererBounds(GameObject theObject) { Bounds returnBounds; // if the object has a renderer at root level, we base our calculations on that if (theObject.GetComponent()!=null) { returnBounds = theObject.GetComponent().bounds; return returnBounds; } // if the object contains at least one renderer we'll add all its children's renderer bounds if (theObject.GetComponentInChildren()!=null) { Bounds totalBounds = theObject.GetComponentInChildren().bounds; Renderer[] renderers = theObject.GetComponentsInChildren(); foreach (Renderer renderer in renderers) { totalBounds.Encapsulate(renderer.bounds); } returnBounds = totalBounds; return returnBounds; } returnBounds = new Bounds(Vector3.zero, Vector3.zero); return returnBounds; } } }