TransformExtensions.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using UnityEditor;
  5. namespace O3DWB
  6. {
  7. public static class TransformExtensions
  8. {
  9. #region Extension Methods
  10. public static TransformMatrix GetWorldMatrix(this Transform transform)
  11. {
  12. return new TransformMatrix(transform.position, transform.rotation, transform.lossyScale);
  13. }
  14. public static TransformMatrix GetRelativeTransformMatrix(this Transform transform, Transform referenceTransform)
  15. {
  16. // Note: Careful! Does not take into account the scale sign. Only works when the sign of the scale is not important.
  17. Matrix4x4 relativeMatrix = referenceTransform.localToWorldMatrix.inverse * transform.localToWorldMatrix;
  18. return new TransformMatrix(relativeMatrix);
  19. }
  20. public static TransformMatrix GetRelativeTransformMatrix(this Transform transform, TransformMatrix referenceTransform)
  21. {
  22. // Note: Careful! Does not take into account the scale sign. Only works when the sign of the scale is not important.
  23. Matrix4x4 relativeMatrix = referenceTransform.ToMatrix4x4x.inverse * transform.localToWorldMatrix;
  24. return new TransformMatrix(relativeMatrix);
  25. }
  26. public static List<Transform> GetImmediateChildTransforms(this Transform transform)
  27. {
  28. var childTransforms = new List<Transform>();
  29. for (int childIndex = 0; childIndex < transform.childCount; ++childIndex )
  30. {
  31. childTransforms.Add(transform.GetChild(childIndex));
  32. }
  33. return childTransforms;
  34. }
  35. public static void SetWorldScale(this Transform transform, Vector3 worldScale)
  36. {
  37. Transform transformParent = transform.parent;
  38. transform.parent = null;
  39. transform.localScale = worldScale;
  40. transform.parent = transformParent;
  41. }
  42. public static void InheritWorldTransformFrom(this Transform destinationTransform, Transform sourceTransform)
  43. {
  44. destinationTransform.position = sourceTransform.position;
  45. destinationTransform.rotation = sourceTransform.rotation;
  46. destinationTransform.localScale = sourceTransform.localScale;
  47. //destinationTransform.SetWorldScale(sourceTransform.lossyScale);
  48. }
  49. public static void InheritLocalTransformFrom(this Transform destinationTransform, Transform sourceTransform)
  50. {
  51. destinationTransform.localPosition = sourceTransform.localPosition;
  52. destinationTransform.localRotation = sourceTransform.localRotation;
  53. destinationTransform.localScale = sourceTransform.localScale;
  54. }
  55. #endregion
  56. }
  57. }
  58. #endif