Unity3D动态修改RectTransform

Unity3D动态修改RectTransform

改变RectTransform的width,height

GetComponent().rect.width、GetComponent().rect.height以及GetComponent().width、GetComponent().height都是只读的,不能直接更改。

那么,要重新设置UI界面的RectTransform中的长和宽,我们可以使用GetComponent().sizeDelta,重新定义sizeDelta就好了。

GetComponent().sizeDelta = new Vector2(new width,new height);

 

拓展:

1.改变RectTransform的Left和Buttom

Unity3D动态修改RectTransform_第1张图片

GetComponent().offsetMin = new Vector2(left, bottom);

  • offsetMin.x:为RectTransform中的Left,即offsetMin.x = left
  • offsetMin.y:为RectTransform中的Buttom,即offsetMin.y = bottom

若获取LeftBottom的值:

  • float left = GetComponent().offsetMin.x;
  • float bottom = GetComponent().offsetMin.y;

2.改变RectTransform的Right和Top

GetComponent().offsetMax = new Vector2(right, top);

  • offsetMax.x:为RectTransform中的Right,即offsetMax.x = -right
  • offsetMax.y:为RectTransform中的Top,即offsetMax.y = -top

若获取RightTop的值:

  • float right = -GetComponent().offsetMax.x;
  • float top = -GetComponent().offsetMax.y;

3.改变RectTransform的pos

(1) anchoredPosition3D,修改Pos

        GetComponent().anchoredPosition3D = new Vector3(posx,posy,posz); 

(2) anchoredPosition,修改Pivot

Unity3D动态修改RectTransform_第2张图片

        GetComponent().anchoredPosition = new Vector2(posx,posy);

你可能感兴趣的:(unity3D,C#,UGUI,unity3d,c#,ugui)