BoundingBoxUtils.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class BoundingBoxUtils
  5. {
  6. public static void ApplyMaterialToAllRenderers(GameObject root, Material material)
  7. {
  8. if (material != null)
  9. {
  10. Renderer[] renderers = root.GetComponentsInChildren<Renderer>();
  11. for (int i = 0; i < renderers.Length; ++i)
  12. {
  13. renderers[i].sharedMaterial = material;
  14. }
  15. }
  16. }
  17. public static Bounds GetMaxBounds(GameObject g)
  18. {
  19. var b = new Bounds();
  20. Mesh currentMesh;
  21. foreach (MeshFilter r in g.GetComponentsInChildren<MeshFilter>())
  22. {
  23. if ((currentMesh = r.sharedMesh) == null) { continue; }
  24. if (b.size == Vector3.zero)
  25. {
  26. b = currentMesh.bounds;
  27. }
  28. else
  29. {
  30. b.Encapsulate(currentMesh.bounds);
  31. }
  32. }
  33. return b;
  34. }
  35. /// <summary>
  36. /// Transforms the size from local to world.
  37. /// </summary>
  38. /// <param name="transform">The transform.</param>
  39. /// <param name="localSize">The local size.</param>
  40. /// <returns>World size.</returns>
  41. public static Vector3 TransformSize(Transform transform, Vector3 localSize)
  42. {
  43. Vector3 transformedSize = new Vector3(localSize.x, localSize.y, localSize.z);
  44. Transform t = transform;
  45. do
  46. {
  47. t = t.parent;
  48. if (t != null)
  49. {
  50. transformedSize.x *= t.localScale.x;
  51. transformedSize.y *= t.localScale.y;
  52. transformedSize.z *= t.localScale.z;
  53. }
  54. }
  55. while (t != null);
  56. return transformedSize;
  57. }
  58. }