Skip to content

Instantly share code, notes, and snippets.

@Parell
Last active November 3, 2023 19:53
Show Gist options
  • Save Parell/8ae5fb3347bd28ffc50094bc0910b8cf to your computer and use it in GitHub Desktop.
Save Parell/8ae5fb3347bd28ffc50094bc0910b8cf to your computer and use it in GitHub Desktop.
Unity game engine local bounds script with child component encapsulation.
using UnityEngine;
public static class BoundsExtension : MonoBehaviour
{
public static Bounds LocalBounds(GameObject parentObject)
{
List<MeshFilter> meshs = new List<MeshFilter>();
meshs.AddRange(parentObject.GetComponentsInChildren<MeshFilter>());
Debug.Log(meshs.Count);
Bounds finalBounds = new Bounds();
for (int i = 0; i < meshs.Count; i++)
{
var meshTransform = meshs[i].transform;
var bounds = meshs[i].mesh.bounds;
var size = bounds.size;
size.x *= meshTransform.localScale.x;
size.y *= meshTransform.localScale.y;
size.z *= meshTransform.localScale.z;
bounds.size = size + 2 * meshTransform.localPosition;
finalBounds.Encapsulate(bounds);
}
Debug.Log(finalBounds.size);
Debug.Log(finalBounds.extents);
Debug.Log(finalBounds.center);
return finalBounds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment