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

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?

public Text output;
Vector2 rectSize = output.GetComponent<RectTransform>().sizeDelta;
rectSize = new Vector2 (rectSize.x, rectSize.y + 2);

EDIT:

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

output.rectTransform.sizeDelta = rectSize;

You never set the new size.

output.rectTransform.sizeDelta = rectSize;

A better way to do this would be…

output.rectTransform.sizeDelta = new Vector2 (output.rectTransform.rect.width, output.rectTransform.rect.height + 2);
1 Like

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.

2 Likes

Bingo! That makes perfect sense. I think I possibly stared at this puzzle too long! xD

Thanks!

//Lam

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! :slight_smile:

THANK YOU:smile:
Ran into this from inside a coroutine. Was able to fix it just by adding

yield return new WaitForEndOfFrame();

before I modified sizeDelta.

2 Likes

LayoutRebuilder.ForceRebuildLayoutImmediate( myRect.rectTransform );
is the way to force a transform update if not in a coroutine