using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextUpdate : MonoBehaviour { List allTexts = new List(); string content = string.Empty; Font fontData = null; FontStyle fontStyle; int fontSize = 14; float lineSpacing = 0f; bool richText = true; TextAnchor alignment; HorizontalWrapMode hwmode; VerticalWrapMode vwmode; Color m_Color; Material m_Material; bool raycastTarget; [ContextMenu("UpdateText")] public void UpdateText() { FindAllText(); for (int i = allTexts.Count - 1; i >= 0; i--) { var text = allTexts[i]; if (text != null) { content = text.text; fontData = text.font; fontStyle = text.fontStyle; fontSize = text.fontSize; lineSpacing = text.lineSpacing; richText = text.supportRichText; alignment = text.alignment; hwmode = text.horizontalOverflow; vwmode = text.verticalOverflow; m_Color = text.color; m_Material = text.material; raycastTarget = text.raycastTarget; var gameObject = text.gameObject; Component.DestroyImmediate(text); TextEx textex = gameObject.AddMissingComponent(); textex.text = content; textex.font = fontData; textex.fontStyle = fontStyle; textex.fontSize = fontSize; textex.lineSpacing = lineSpacing; textex.supportRichText = richText; textex.alignment = alignment; textex.horizontalOverflow = hwmode; textex.verticalOverflow = vwmode; textex.color = m_Color; textex.material = m_Material; textex.raycastTarget = raycastTarget; } } } void FindAllText() { allTexts.Clear(); FindChildText(this.transform, ref allTexts); } void FindChildText(Transform _transform, ref List _allTexts) { if (_transform != null) { var text = _transform.GetComponent(); if (text != null) { _allTexts.Add(text); } for (int i = 0; i < _transform.childCount; i++) { FindChildText(_transform.GetChild(i), ref _allTexts); } } } #region 字色替换 [SerializeField] Color m_BeforeColor = Color.white; [SerializeField] Color m_AfterColor = Color.white; [ContextMenu("替换字色")] public void UpdateTextColor() { FindAllText(); for (int i = allTexts.Count - 1; i >= 0; i--) { if (allTexts[i].color.Equals(m_BeforeColor)) { allTexts[i].color = m_AfterColor; } } } #endregion }