Search Unity

Question Can I use a sprite's pivot in a UI Image component

Discussion in 'UGUI & TextMesh Pro' started by Toreth, Nov 21, 2020.

  1. Toreth

    Toreth

    Joined:
    Apr 8, 2017
    Posts:
    31
    I've got a sprite sheet where all of the sprites are aligned with the bottom of the frame. When I sliced my sprite sheet, I set the pivot's Y to 0.4 to account for this. When I draw sprites animations in the game, that works correctly and the sprites are aligned how I want them to be. However, when I add one of those sprites to an Image UI component, the pivot gets ignored and the sprite is aligned with the bottom of the Image's position. Is there a way to make the Image component use the sprite's pivot point?

    Moving the Image component up or down won't work as a solution because the Image component will sometimes display sprites with a pivot of (0.5, 0.5) and will sometimes display sprites with a custom pivot.
     
  2. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    Using this for my game.

    Extension Method:
    Code (CSharp):
    1. public static void CenterSpriteOnPivotY(this Image img)
    2.         {
    3.             float offsetY = img.rectTransform.rect.height * Mathf.Abs((img.sprite.pivot.y / img.sprite.rect.height) - .5f);
    4.  
    5.             img.rectTransform.offsetMin = new Vector2(img.rectTransform.offsetMin.x, -offsetY);
    6.             img.rectTransform.offsetMax = new Vector2(img.rectTransform.offsetMax.x, -offsetY);
    7.         }
     
  3. bogdanmichon14

    bogdanmichon14

    Joined:
    Apr 9, 2018
    Posts:
    2
    Do you then create a script, that triggers this Method on a specific Image component? or is there a easier way?