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

    }
}
发布了56 篇原创文章 · 获赞 24 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u014196765/article/details/94335813