UGUI的Text自己是没有下划线或者文字中间的划去横线的。使用此组件,选择Text和划线类型:
1.设置autoLink=true,运行后自动克隆相同的文本组件,计算文字长度,给克隆的Text填充"_"或者"-";
2.调用CreateLink方法,为指定Text文本添加下划线
3.此组件暂时用于固定文本,或仅用于一次展示的文本,同一个文本动态修改的时候应当先删除子物体中的下划线文本
如:给Text添加UnderLineText组件,设置LinkText为自己,UnderLineType为Bottom,AutoLink=true;
运行后会为原来的Text添加一个子物体Text组件,填充“___”
另:文本中有回车时候会无法转换。
完整代码:
using UnityEngine; using System.Collections; using UnityEngine.UI; public enum UnderLineType { //画线位置 Bottom = 0, Center } //文本编辑扩展 public class UnderLineText : MonoBehaviour { public Text linkText; public UnderLineType underLineType; public bool autoLink = true; private string underLineText = "_"; private void Awake() { if (underLineType == UnderLineType.Bottom) { underLineText = "_"; } else { underLineText = "-"; } } private void Start() { if (autoLink) CreateLink(linkText, null); } public void CreateLink(Text text, UnityEngine.Events.UnityAction onClickBtn = null) { if (text == null) return; //克隆Text,获得相同的属性 Text underline = Instantiate(text) as Text; underline.name = "Underline"; underline.transform.SetParent(text.transform); underline.transform.localScale = Vector3.one; RectTransform rt = underline.rectTransform; //设置下划线坐标和位置 rt.anchoredPosition3D = Vector3.zero; rt.offsetMax = Vector2.zero; rt.offsetMin = Vector2.zero; rt.anchorMax = Vector2.one; rt.anchorMin = Vector2.zero; underline.text = underLineText; float perlineWidth = underline.preferredWidth; //单个下划线宽度 float width = text.preferredWidth; int lineCount = (int)Mathf.Round(width / perlineWidth); for (int i = 1; i < lineCount; i++) { underline.text += underLineText; } if (onClickBtn != null) { var btn = text.gameObject.AddComponent<Button>(); btn.onClick.AddListener(onClickBtn); } var underLine = underline.GetComponent<UnderLineText>(); if (underLine) { underLine.autoLink = false; } } }