Unity dynamically changes the position and width and height of RectTransform in the code


Link to the original text (respect the original): [100 Unity Practical Skills] | Unity dynamically changes the RectTransform position and width and height in the code.

Unity Practical skills to learn
how to dynamically change the position, width and height of RectTransform in code Organize
RectTransform official website API address: https://docs.unity3d.com/2020.3/Documentation/ScriptReference/RectTransform.html

Today, let’s talk about the method of dynamically changing the size, width and height of RectTransform in the code. There are many parameters and methods of RectTransform, so I won’t introduce them here.

Sometimes we want to use code to adjust the parameters of RectTransform, including position and size, so we sorted out several commonly used API methods.
———————————————

1. Three ways to change the size of RectTransform

        //1.直接对sizeDelta属性进行赋值,其中X和Y可以对应理解成width和height。sizeDelta的具体含义:若achors是一个点的话则代表宽高,否则为到锚点的距离
        rectTransform.sizeDelta = new Vector2(200, 200);
        //2.使用SetSizeWithCurrentAnchors函数来进行设定,其中Horizontal和Vertical分别对应宽和高。此函数受当前锚点和中心点的影响。
        rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, posx);
        rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, posy);
        //3.使用SetInsetAndSizeFromParentEdge函数来进行设定。此函数不受锚点和中心的影响,其中第一个参数代表对齐方式,第二个参数为距离边界的距离,第三个参数为宽度。
        rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 100, posx);
        rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, posy);

Two, change the position of RectTransform Position

rectTransform.anchoredPosition = new Vector2(posx, posy);
rectTransform.anchoredPosition3D = new Vector3(posx, posy, posz);

3. Change the top of RectTransform

 rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, 200);

4. Change the bottom of RectTransform

rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, 100);

Guess you like

Origin blog.csdn.net/qq_37524903/article/details/131090571