/******************************************************************** 文件: CommonExtension.cs 作者: 梦语 邮箱: 1982614048@qq.com 创建时间: 2024/04/11 14:55:52 最后修改: 梦语 最后修改时间: 2024/04/22 20:18:33 功能: *********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; namespace Ether { public static class CommonExtension { #region UI自适应 #region 文本自适应大小 /// /// Text根据内容适配大小 /// /// public static void SetAutoSize(this TextMeshProUGUI text, float addWidth = 0, float addHeight = 0) { RectTransform rect = text.GetComponent(); // 动态设置width rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, text.preferredWidth + addWidth); // 动态设置height rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, text.preferredHeight + addHeight); } /// /// Text根据内容适配高度 /// /// public static void SetAutoHeight(this TextMeshProUGUI text, float addSize = 0) { RectTransform rect = text.GetComponent(); // 获取Text的Size Vector2 rectSize = rect.rect.size; // width不变 rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, rectSize.x); // 动态设置height rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, text.preferredHeight + addSize); } /// /// Text根据内容适配宽度 /// /// public static void SetAutoWidth(this TextMeshProUGUI text, float addSize = 0) { RectTransform rect = text.GetComponent(); // 获取Text的Size Vector2 rectSize = rect.rect.size; // 动态设置width rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, text.preferredWidth + addSize); // height不变 rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, rectSize.y); } #endregion #region UI大小设置 public static void SetWidth(this GameObject go, float width) { RectTransform rect = go.GetComponent(); //rect.sizeDelta = new Vector2(width, rect.sizeDelta.y); rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width); } public static void SetHeight(this GameObject go, float height) { RectTransform rect = go.GetComponent(); //rect.sizeDelta = new Vector2(rect.sizeDelta.x, height); rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height); } public static void SetSize(this GameObject go, Vector2 size) { RectTransform rect = go.GetComponent(); //rect.sizeDelta = size; rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, size.x); rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, size.y); } public static Vector3 GetSize(this GameObject obj) { RectTransform rect = obj.GetComponent(); return rect.rect.size; } #endregion #endregion /// /// 设置物体显示和隐藏 /// public static void SetVisible(this GameObject go, bool visible, Action callback = null) { if (!go) { return; } if (go.activeSelf == visible) { return; } if (visible) { go.SetActive(true); callback?.Invoke(); } else { AnimController anim = go.GetComponent(); if (anim != null) { anim.PlayDisableAnim(() => { callback?.Invoke(); go.SetActive(visible); }); } else { callback?.Invoke(); go.SetActive(visible); } } } } }