Unity 在代码中 动态改变RectTransform位置及宽高 的方法整理


原文链接(尊重原著):【100个 Unity实用技能】 | Unity 在代码中 动态改变RectTransform位置及宽高 的方法整理_unity 修改recttransform_呆呆敲代码的小Y的博客-CSDN博客

Unity 实用小技能学习
Unity 在代码中 动态改变RectTransform位置及宽高 的方法整理
RectTransform官网API地址:https://docs.unity3d.com/2020.3/Documentation/ScriptReference/RectTransform.html

今天来讲一下代码中动态改变RectTransform大小及宽高的方法,关于RectTransform的参数和方法还有很多,这里不多做介绍。

有时候我们希望可以使用代码来调节RectTransform的各项参数,包括位置及大小,所以来整理了几种常用的API方法。
————————————————

一、改变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);

二、改变RectTransform的位置Position

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

三、改变RectTransform的top

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

四、改变RectTransform的bottom

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

猜你喜欢

转载自blog.csdn.net/qq_37524903/article/details/131090571