- Home /
How do i set the width/height of a UI element?
this seems simple, but i cant figure it out. the rectTransform has no width or height parameter. Its rect parameter has a width parameter which is readonly, and the rect itself is also readonly so i can't write another rect over it
how do i actually change the width of a ui element from code?
You can't set width and heigh directly. You must play with sizeDelta.
can also change scale
GetComponent.<RectTransform>().localScale = Vector3(1, 1, 1);
Answer by Gnorpelzwerg · Jan 15, 2017 at 12:06 PM
GetComponent< RectTransform >( ).SetSizeWithCurrentAnchors( RectTranform.Axis.Vertical, myHeight);
worked for me. For width use: RectTransform.Axis.Horizontal
.
Answer by robbagus · May 20, 2015 at 06:26 AM
yourUIElement.GetComponent(RectTransform).sizeDelta = new Vector2 (width, height);
Do bear in mind that the size is relative to your UI anchor.
Answer by paddywwoof · Mar 08, 2019 at 06:54 PM
or I used this method for a tiled image as a health bar.
health_bar.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, HEALTH_LEFT, health * HEALTH_UNIT);
Answer by badadam · Mar 08, 2019 at 08:01 PM
Try this code
yourUI.rectTransform.sizeDelta = new Vector2(newWidthUI,newHeightUI);
@badadam Hi, with a health bar type thing the rectangle of tiled images needs to have its width changed then the left side moved by half the change in width. Possibly also adjusted for any scaling used in the UI element. So for that kind of thing the SetInsetAndSizeFromParentEdge takes care of scaling and moving to the correct location.
Paddy
Answer by Shadow2359 · May 20, 2015 at 06:27 AM
If your UI element is a child of the RectTransform component you can use RectTransform.sizeDelta:Vector2 which will scale the UI element in the vertical and horizonal axis up to the anchor points, kinda like a scale function. If it doesn't need to be done in code you should be able to set the width and height in the inspector once you add the Rect Transform component to the game object that is going to house the UI element (I'm assuming a text element). If it does have to be done in script try looking below to see if to see any better alternatives to sizeDelta which I'm sure there are...
Your answer
Follow this Question
Related Questions
Get height and width of gameobject set with anchors 0 Answers
UI 4.6: custom anchors breaking sizeDelta 0 Answers
Incorrect RectTransform width value when trying to read child RectTransform width. 0 Answers
How to change the Width and Height in the script C#? (New Gui Unity 4.6 beta) 2 Answers
UI Vertical Layout Group with Content Size Fitter, how to set max width? 1 Answer