TransformExtensions.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. namespace SRF
  2. {
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public static class SRFTransformExtensions
  6. {
  7. public static IEnumerable<Transform> GetChildren(this Transform t)
  8. {
  9. var i = 0;
  10. while (i < t.childCount)
  11. {
  12. yield return t.GetChild(i);
  13. ++i;
  14. }
  15. }
  16. /// <summary>
  17. /// Reset all local values on a transform to identity
  18. /// </summary>
  19. /// <param name="t"></param>
  20. public static void ResetLocal(this Transform t)
  21. {
  22. t.localPosition = Vector3.zero;
  23. t.localRotation = Quaternion.identity;
  24. t.localScale = Vector3.one;
  25. }
  26. /// <summary>
  27. /// Create an empty child object of this transform
  28. /// </summary>
  29. /// <param name="t"></param>
  30. /// <param name="name"></param>
  31. /// <returns></returns>
  32. public static GameObject CreateChild(this Transform t, string name)
  33. {
  34. var go = new GameObject(name);
  35. go.transform.parent = t;
  36. go.transform.ResetLocal();
  37. go.gameObject.layer = t.gameObject.layer;
  38. return go;
  39. }
  40. /// <summary>
  41. /// Set the parent of this transform, but maintain the localScale, localPosition, localRotation values.
  42. /// </summary>
  43. /// <param name="t"></param>
  44. /// <param name="parent"></param>
  45. public static void SetParentMaintainLocals(this Transform t, Transform parent)
  46. {
  47. t.SetParent(parent, false);
  48. }
  49. /// <summary>
  50. /// Copy local position,rotation,scale from other transform
  51. /// </summary>
  52. /// <param name="t"></param>
  53. /// <param name="from"></param>
  54. public static void SetLocals(this Transform t, Transform from)
  55. {
  56. t.localPosition = from.localPosition;
  57. t.localRotation = from.localRotation;
  58. t.localScale = from.localScale;
  59. }
  60. /// <summary>
  61. /// Set position/rotation to from. Scale is unchanged
  62. /// </summary>
  63. /// <param name="t"></param>
  64. /// <param name="from"></param>
  65. public static void Match(this Transform t, Transform from)
  66. {
  67. t.position = from.position;
  68. t.rotation = from.rotation;
  69. }
  70. /// <summary>
  71. /// Destroy all child game objects
  72. /// </summary>
  73. /// <param name="t"></param>
  74. public static void DestroyChildren(this Transform t)
  75. {
  76. foreach (var child in t)
  77. {
  78. Object.Destroy(((Transform) child).gameObject);
  79. }
  80. }
  81. }
  82. }