In Unity, Transform can be used to control the movement, scaling and rotation of 3d objects. How to set Transform in Canvas? You can use RectTransform, which inherits from Transform.
// RectTransform a = this. Transform. Getcomponent < RectTransform > (); / / get the RectTransform by getting the component. RectTransform a = this.transform as RectTransform;//Get RectTransform by as keyword
Move the location of the element: you can't use a.position = new Vector3() directly, which can also be set, but you don't know where to set it. To use the following UI specific parameter settings.
a.anchoredPosition=new Vector2(10,10);//Set the location of UI elements a.anchoredPosition3D = new Vector3(10,10,10);//Set the location of the UI element. The above is 2d, and this is 3d.
Get the properties of UI elements and read them through rect. This parameter is read-only and cannot be set.
Debug.Log("Width:"+a.rect.width) ; Debug.Log("Height:"+a.rect.height) ; Debug.Log("Orientation: bottom"+a.rect.bottom+" right: "+a.rect.right);
Set the width and height of the elements of the UI:
//a.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,300); / / set width //a.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,100); / / set height
Here is the code I tested.
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 > (); / / get 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("Width:"+a.rect.width) ; Debug.Log("Height:"+a.rect.height) ; Debug.Log("Orientation: bottom"+a.rect.bottom+" right: "+a.rect.right); Debug.Log(a.sizeDelta); // a.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,300); // a.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,100); } }