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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值