欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 在代码中动态改变RectTransform大小的方法

程序员文章站 2022-06-11 09:13:10
...
1:直接对sizeDelta属性进行赋值,其中X和Y可以对应理解成width和height。sizeDelta的具体含义:若achors是一个点的话则代表宽高,否则为到锚点的距离
var rt = gameObject.GetComponent<RectTransform>();  
rt.sizeDelta = new Vector2(100, 30);  

2:使用SetSizeWithCurrentAnchors函数来进行设定,其中Horizontal和Vertical分别对应宽和高。此函数受当前锚点和中心点的影响。
var rt = gameObject.GetComponent<RectTransform>();  
rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 100);  
rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 30);  

3:使用SetInsetAndSizeFromParentEdge函数来进行设定。此函数不受锚点和中心的影响,其中第一个参数代表对齐方式,第二个参数为距离边界的距离,第三个参数为宽度。
var rt = gameObject.GetComponent<RectTransform>();  
rt.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 100);  
rt.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, 30);