Set UI element pivot to parent position?

Hi all,

so I have an inventory system with, well, slots and items. An item has a Button, Image and Text.

UI
– Inventory
---- Slots
---- Items
------ Gun (has Button and Image)
-------- Text (has Text)

The player could hold and rotate items. I want the text to stay at the bottom left corner of the item and have its rotation fixed. I managed to fixed the rotation and everything works well ‘if’ I set the pivot of “Text” to the center of “Gun” - (note that “Gun”'s pivot is at its center). Since I generate the items at runtime I have to set the pivot from code, but I’m not sure how… I know what the pivot values represent, 0,0 bottomleft, 1,1 topright the UI element but in my case the pivot has to go out of its UI rectangle.

Setting the pivot manually in the editor, I got “2.1, 3.0” which I couldn’t deduce anything from… So how do I set the Text’s pivot to the position of its parent element?

Cheers.

Bump

I think you might be overcomplicating this somewhat.

This script will prevent the text from changing orientation, relative to it’s parent:
It’s been placed on the parent object, which would be the gun/button.

public class TextTransformFixer : MonoBehaviour {

    Text text;
    Vector3 savedAbsolutePosition;

    void Start () {
        text = transform.Find ("Text").GetComponent<Text>();
        savedAbsolutePosition = text.transform.position;
    }

 
    void Update () {
        FixTextPosition();
    }

    void FixTextPosition(){

        text.transform.rotation = Quaternion.identity;
        text.transform.position = savedAbsolutePosition;
    }
}

That being said, I would change your hierarchy to look like this:

Blank UI Element

  • Rotating Image Element
  • Text Element

That way you don’t have to have a scripted solution, what-so-ever.

Example enclosed as a unity package.

1889079–121553–InventoryItemExample.unitypackage (109 KB)