Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Accessing a UI element's dimension (width/height) from code is not so very intuitive?

Discussion in 'UGUI & TextMesh Pro' started by vexe, Sep 1, 2014.

  1. vexe

    vexe

    Joined:
    May 18, 2013
    Posts:
    644
    Hi all,

    one thing I found a bit tricky, is changing the width/height of a UI element from code. I really didn't know which property is relevant but I noticed in the RectTransform sometimes there's 'width'/'height' written or bottom/right - There was no width/height properties code-wise - So I wanted to know what values they're displaying in their editor so I took at a peek at their RectTransform editor and saw that it's 'deltaSize' - It turns out that depending on your anchor configuration, this size could act as width/height or an offset. Not very straight forward, nor counter-intuitive. I'd be nice if there's a straight-forward way to manipulate the width/height directly.

    Am I missing something? - What is the proper way to access (get&set) a UI element's (say Image) dimensions (width/height) from code regardless of anchor settings?

    Cheers.
     
    Kylotan likes this.
  2. JAKJ

    JAKJ

    Joined:
    Aug 17, 2014
    Posts:
    185
    sizeDelta is always the width/height: Depending on your anchor configuration will change how increasing/decreasing the width/height moves the element, but it will still be the width/height. Same for anchoredPosition: Use that to change the "x/y" value of the element.

    If you stick to sizeDelta and anchoredPosition, and set up your anchors properly, moving things on the UI will become easy and consistent.
     
    Nanity and rakkarage like this.
  3. hersheys72

    hersheys72

    Joined:
    Sep 4, 2015
    Posts:
    7
    In the RectTransform component in the Inspector, just above the Anchors tab there is an anchor presets button. If you set this one to the middle centre option (the one with the red lines through it horiz and vert) then the
    GetComponent<RectTransform>().rect.width works fine, whereas with the stretch options it gives weird results probably due to the anchors positioning changing.
     

    Attached Files: