Unity3D动态修改RectTransform
改变RectTransform的width,height
GetComponent<RectTransform>().rect.width、GetComponent<RectTransform>().rect.height以及GetComponent<Rect>().width、GetComponent<Rect>().height都是只读的,不能直接更改。
那么,要重新设置UI界面的RectTransform中的长和宽,我们可以使用GetComponent<RectTransform>().sizeDelta,重新定义sizeDelta就好了。
GetComponent<RectTransform>().sizeDelta= new Vector2(new width,new height);
拓展:
1.改变RectTransform的Left和Buttom
GetComponent<RectTransform>().offsetMin = new Vector2(left, bottom);
offsetMin.x:为RectTransform中的Left,即offsetMin.x = left;offsetMin.y:为RectTransform中的Buttom,即offsetMin.y = bottom。
若获取Left、Bottom的值:
float left= GetComponent<RectTransform>().offsetMin.x;float bottom= GetComponent<RectTransform>().offsetMin.y;
2.改变RectTransform的Right和Top
GetComponent<RectTransform>().offsetMax = new Vector2(right, top);
offsetMax.x:为RectTransform中的Right,即offsetMax.x = -right;offsetMax.y:为RectTransform中的Top,即offsetMax.y = -top。
若获取Right、Top的值:
float right= -GetComponent<RectTransform>().offsetMax.x;float top= -GetComponent<RectTransform>().offsetMax.y;
3.改变RectTransform的pos
(1)anchoredPosition3D,修改Pos
GetComponent<RectTransform>().anchoredPosition3D = new Vector3(posx,posy,posz);
(2)anchoredPosition,修改Pivot
GetComponent<RectTransform>().anchoredPosition = new Vector2(posx,posy);