Unity 十五 UGUI RectTransform 脚本控制

在Unity里可以 Transform 控制3d 物体的移动缩放旋转,那么在 Canvas 里如何设置 transform 呢,可以用 RectTransform,它继承于 Transform。

//    RectTransform     a = this.transform.GetComponent<RectTransform>();//通过获取组件,获取 RectTransform
  RectTransform      a = this.transform as RectTransform;//通过 as 关键字获得 RectTransform

移动元素的位置:不能直接用 a.position = new Vector3(),这样也可以设置,但是不知道设置到什么地方去了。要用下面的 UI 特定的参数设置。

       a.anchoredPosition=new Vector2(10,10);//设置 UI 元素的位置
       a.anchoredPosition3D = new Vector3(10,10,10);//设置 UI 元素的位置,上面是2d,这个是3d 的。

获取 UI 元素的属性,通过 rect来读取。这个参数下是只读参数,不能 set

 Debug.Log("宽度:"+a.rect.width) ;
       Debug.Log("高度:"+a.rect.height) ;
       Debug.Log("方位:底部"+a.rect.bottom+" right:"+a.rect.right); 

设置UI 的元素的宽高:
在这里插入图片描述

//        a.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,300);//设置宽度
//        a.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,100);//设置高度

下面是我测试的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonTransform : MonoBehaviour
{
    // Start is called before the first frame update
    private RectTransform a;
    void Start()
    {
//         a = this.transform.GetComponent<RectTransform>();//获取
        a = this.transform as RectTransform;
    }

    // Update is called once per frame
    void Update()
    { 
//        transform.Translate(Vector3.right*Time.deltaTime*50) ;
//        a.anchoredPosition=new Vector2(10,10);
//        a.anchoredPosition3D = new Vector3(10,10,10);
       Debug.Log("宽度:"+a.rect.width) ;
       Debug.Log("高度:"+a.rect.height) ;
       Debug.Log("方位:底部"+a.rect.bottom+" right:"+a.rect.right); 
       Debug.Log(a.sizeDelta);  
//        a.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,300);
//        a.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,100);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小~小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值