Search Unity

[Resolved] Changing height of RectTransform.sizeDelta via c# script doesn't update box.

Discussion in 'UGUI & TextMesh Pro' started by Lamargo, Apr 13, 2015.

  1. Lamargo

    Lamargo

    Joined:
    Mar 22, 2015
    Posts:
    4
    Hi,

    I've been trying to following examples on how to use sizeDelta to change the height of a Text box via code, and although the following does show the change to "height" via Debug.Log, the change in height doesn't apply to the object itself, so on each pass it pulls in the same height value, adds 2, but then this doesn't seem to be set on the text box's RectTransform during runtime. On the next pass it is back to the default values and goes no further.

    Any ideas?

    Code (CSharp):
    1. public Text output;
    2. Vector2 rectSize = output.GetComponent<RectTransform>().sizeDelta;
    3. rectSize = new Vector2 (rectSize.x, rectSize.y + 2);
    EDIT:

    added the following line to have it working - thanks to KrayZLogic for the correction.

    Code (CSharp):
    1. output.rectTransform.sizeDelta = rectSize;
     
    Last edited: Apr 13, 2015
  2. KrayZLogic

    KrayZLogic

    Joined:
    Jun 19, 2013
    Posts:
    55
    You never set the new size.

    Code (CSharp):
    1. output.rectTransform.sizeDelta = rectSize;
    A better way to do this would be...

    Code (CSharp):
    1. output.rectTransform.sizeDelta = new Vector2 (output.rectTransform.rect.width, output.rectTransform.rect.height + 2);
     
    Lamargo likes this.
  3. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,689
    Also make sure you update the sizeDelta in LateUpdate().

    This is due to the processing order that the UI undergoes when rendering. Changes in the Update loop may get overwritten by the UI system.
     
    apatton and Lamargo like this.
  4. Lamargo

    Lamargo

    Joined:
    Mar 22, 2015
    Posts:
    4
    Bingo! That makes perfect sense. I think I possibly stared at this puzzle too long! xD

    Thanks!

    //Lam
     
  5. Lamargo

    Lamargo

    Joined:
    Mar 22, 2015
    Posts:
    4
    There's nothing overly complex going on here, so it's not necessary to do this at this stage, but will bear it in mind, thanks! :)
     
  6. apatton

    apatton

    Joined:
    Sep 7, 2013
    Posts:
    8
    THANK YOU:D
    Ran into this from inside a coroutine. Was able to fix it just by adding
    Code (CSharp):
    1. yield return new WaitForEndOfFrame();
    before I modified sizeDelta.
     
    Fep310 and SimonDarksideJ like this.
  7. mrVentures

    mrVentures

    Joined:
    Nov 11, 2018
    Posts:
    9
    LayoutRebuilder.ForceRebuildLayoutImmediate( myRect.rectTransform );
    is the way to force a transform update if not in a coroutine