- Home /
RectTransform won't Resize
Not sure what's wrong exactly but when I attempt to change the width of my UI textObject through script, it compiles nothing happens.
#pragma strict
function Start () {
SetText();
}
function SetText(){
//There are seperate objects for the nameplace and text that a character will say and their rect's are accessed here
var nameRect : RectTransform = GameObject.Find("Name").GetComponent.<RectTransform>();
var textRect : RectTransform = GameObject.Find("Speech").GetComponent.<RectTransform>();
//Both positionings relative to the screen width and height work
nameRect.anchoredPosition = Vector2(Screen.width*(-0.4), Screen.height*(-0.2));
textRect.anchoredPosition = Vector2(0, Screen.height*(-0.25));
//before width is accessed
print(textRect.rect.width);
//accessing the rect's width
textRect.rect.width = Screen.width*0.9;
//checking to see if anything's changed
print(textRect.rect.width);
}
When I'm in the editor I can change the width just fine, but I can't seem to access it through. I don't think width is ReadOnly and I've tried changing the width using the sizeDelta component of rectTransform with the same null result. Please and Thank you~! I hope this isn't a bug...
Answer by DiegoSLTS · May 24, 2015 at 11:32 PM
RectTransform's "rect" member is a property that gets calculated when you ask for it, and a new Rect instance is returned. If you change the width and height of that rect you're not changing the size of the element, just the size of some rect.
If you want to change the width you have to change the sizeDelta property, but how that property changes the size of the UI element depends on it's anchor. According to the docs (http://docs.unity3d.com/es/current/ScriptReference/RectTransform-sizeDelta.html):
If the anchors are together, sizeDelta is the same as size. If the anchors are in each of the four corners of the parent, the sizeDelta is how much bigger or smaller the rectangle is compared to its parent.
Also, note that "changing sizeDelta" means assigning a whole new value to it, you can't just change the x or y property because sizeDelta is also a property that gets calculated each time you ask for it, so you end up with a Vector2 that won't change how the UI looks. The line should look like:
nameRect.sizeDelta = someVector2WithTheNewSize;
Thanks! This worked perfectly! I can see what happened earlier when I attempted to change it with sizeDelta. I didn't care about what it's y was so I tried to edit only the first value the way you usually can with Vector2's using
sizeDelta[0] = Screen.width*0.9; //Vector2[0] = x, Vector2[1] = y
so it compiled but for some reason it wasn't recognized.
Your answer
Follow this Question
Related Questions
RectTransform.rect.Set doesn't work! 1 Answer
How to find width and height of game object, Unity2D 2 Answers
Unity UI Rect 0 Answers
GetComponent() Problem with getting value. 1 Answer
gui texture crop and resize 1 Answer