HundredDojoKeepRelativePos.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. [ExecuteInEditMode]
  6. public class HundredDojoKeepRelativePos : UIBehaviour
  7. {
  8. public RectTransform target;
  9. public RectTransform align;
  10. public RectTransform.Axis axis = RectTransform.Axis.Horizontal;
  11. protected override void OnEnable()
  12. {
  13. base.OnEnable();
  14. KeepPos();
  15. }
  16. protected override void OnRectTransformDimensionsChange()
  17. {
  18. base.OnRectTransformDimensionsChange();
  19. if (!IsActive()) return;
  20. KeepPos();
  21. }
  22. protected override void OnTransformParentChanged()
  23. {
  24. base.OnTransformParentChanged();
  25. if (!IsActive()) return;
  26. KeepPos();
  27. }
  28. private void KeepPos()
  29. {
  30. if (!target || !align)
  31. {
  32. enabled = false;
  33. return;
  34. }
  35. int offset = (int)axis;
  36. Vector3 pos = target.localPosition;
  37. Rect rect = align.rect;
  38. Vector3 pos1 = align.TransformPoint(rect.center);
  39. Transform parent = target.parent;
  40. if (parent)
  41. {
  42. pos1 = parent.InverseTransformPoint(pos1);
  43. }
  44. pos[offset] = pos1[offset];
  45. target.localPosition = pos;
  46. }
  47. }