Unity3D 在代码中动态改变GameObject大小和锚点
  PANeMkgDKlPI 2023年11月02日 23 0

直接对sizeDelta属性进行赋值,其中X和Y可以对应理解成width和height

直接对anchoredPosition3D属性进行赋值,其中X、Y、Z可以对应理解成pos X、pos Y、pos Z

代码

public class ChartsScript : MonoBehaviour
{
public GameObject LeftGameObject;
public Text LeftText;
private Vector2 _sizeDelta;
private Vector3 _anchoredPosition3D;
// Start is called before the first frame update
void Start()
{
_sizeDelta = LeftGameObject.GetComponent<RectTransform>().sizeDelta;
_anchoredPosition3D = LeftGameObject.GetComponent<RectTransform>().anchoredPosition3D;
}

public void FullLeftChart()
{
if (LeftText.text.Equals("全屏"))
{
var width = UnityEngine.Screen.width;
var height = UnityEngine.Screen.height;
var rt = LeftGameObject.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(width, height);
rt.anchoredPosition3D = new Vector3(0, 0, 0);
LeftText.text = "还原";
}
else if (LeftText.text.Equals("还原"))
{
LeftText.text = "全屏";
var rt = LeftGameObject.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(_sizeDelta.x, _sizeDelta.y);
rt.anchoredPosition3D = new Vector3(_anchoredPosition3D.x, _anchoredPosition3D.y, _anchoredPosition3D.z);
}
}
}

效果

Unity3D 在代码中动态改变GameObject大小和锚点_全屏

 如果发现调试的时候不全屏运行,出现点击全屏没有充满屏幕,是因为Canvas Scaler设置的问题

默认是(按屏幕大小缩放)

Unity3D 在代码中动态改变GameObject大小和锚点_游戏引擎_02

修改成Constant Pixel Size(恒定像素大小)即可

Unity3D 在代码中动态改变GameObject大小和锚点_游戏引擎_03


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论