UIImageSetSizeAndPivot.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. using UnityEditor;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. public static class UIImageMenu
  5. {
  6. [MenuItem("GameObject/UI/Set Native Size + Pivot", false, 10000)]
  7. private static void setSizeAndPivot()
  8. {
  9. foreach (GameObject gameObject in Selection.gameObjects)
  10. {
  11. // process all selected game objects which have a RectTransform + Image
  12. RectTransform transform = gameObject.GetComponent<RectTransform>();
  13. Image image = gameObject.GetComponent<Image>();
  14. if (transform && image && image.sprite)
  15. {
  16. // set size as it is defined by source image sprite
  17. image.SetNativeSize();
  18. #if UNITY_2018_1_OR_NEWER
  19. // use mesh defined by source sprite to render UI image
  20. image.useSpriteMesh = true;
  21. #endif
  22. // set pivot point as defined by source sprite
  23. Vector2 size = transform.sizeDelta * image.pixelsPerUnit;
  24. Vector2 pixelPivot = image.sprite.pivot;
  25. // sprite pivot point is defined in pixel, RectTransform pivot point is normalized
  26. transform.pivot = new Vector2(pixelPivot.x / size.x, pixelPivot.y / size.y);
  27. }
  28. }
  29. }
  30. }