TransformExtensions.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. namespace TriLib
  5. {
  6. public static class TransformExtensions
  7. {
  8. public static void LoadMatrix(this Transform transform, Matrix4x4 matrix, bool local = true)
  9. {
  10. if (local)
  11. {
  12. transform.localScale = matrix.ExtractScale();
  13. transform.localRotation = matrix.ExtractRotation();
  14. transform.localPosition = matrix.ExtractPosition();
  15. }
  16. else
  17. {
  18. transform.rotation = matrix.ExtractRotation();
  19. transform.position = matrix.ExtractPosition();
  20. }
  21. }
  22. public static Bounds EncapsulateBounds(this Transform transform)
  23. {
  24. Bounds result = default(Bounds);
  25. Renderer[] componentsInChildren = transform.GetComponentsInChildren<Renderer>();
  26. if (componentsInChildren != null)
  27. {
  28. foreach (Renderer renderer in componentsInChildren)
  29. {
  30. result.Encapsulate(renderer.bounds);
  31. }
  32. }
  33. return result;
  34. }
  35. public static Transform FindDeepChild(this Transform transform, string name, bool endsWith = false)
  36. {
  37. if ((!endsWith) ? transform.name.EndsWith(name) : (transform.name == name))
  38. {
  39. return transform;
  40. }
  41. IEnumerator enumerator = transform.GetEnumerator();
  42. try
  43. {
  44. while (enumerator.MoveNext())
  45. {
  46. object obj = enumerator.Current;
  47. Transform transform2 = (Transform)obj;
  48. Transform transform3 = transform2.FindDeepChild(name, false);
  49. if (transform3 != null)
  50. {
  51. return transform3;
  52. }
  53. }
  54. }
  55. finally
  56. {
  57. IDisposable disposable;
  58. if ((disposable = (enumerator as IDisposable)) != null)
  59. {
  60. disposable.Dispose();
  61. }
  62. }
  63. return null;
  64. }
  65. public static void DestroyChildren(this Transform transform, bool destroyImmediate = false)
  66. {
  67. for (int i = transform.childCount - 1; i >= 0; i--)
  68. {
  69. Transform child = transform.GetChild(i);
  70. if (destroyImmediate)
  71. {
  72. UnityEngine.Object.DestroyImmediate(child.gameObject);
  73. }
  74. else
  75. {
  76. UnityEngine.Object.Destroy(child.gameObject);
  77. }
  78. }
  79. }
  80. }
  81. }