在使用UGUI搭建UI界面時,有時需要對現有的文本内容(Text)添加下劃線。
如果使用文本插件Text Mesh Pro,可以在Inspector界面直接設定。
也可以自己編寫代碼來生成簡單的下劃線。
不多說,上代碼,具體思路參考代碼的注釋。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextUnderLine : MonoBehaviour
{
//目标文本元件
public Text targetText;
// Start is called before the first frame update
private void Start()
{
//建立下劃線
CreatUnderLine();
}
//方法,建立下劃線
private void CreatUnderLine()
{
//空引用直接傳回
if (targetText == null) return;
//複制目标文本的屬性
Text underlineText = Instantiate(targetText) as Text;
//設定下劃線的父物體
underlineText.transform.SetParent(targetText.transform);
//擷取RectTransform元件
RectTransform underlineRT = underlineText.rectTransform;
//設定下劃線的位置
underlineRT.anchoredPosition3D = Vector3.zero;
underlineRT.anchorMax = Vector2.one;
underlineRT.anchorMin = Vector2.zero;
underlineRT.offsetMax = Vector2.zero;
underlineRT.offsetMin = Vector2.zero;
//設定下劃線的縮放
underlineRT.transform.localScale = Vector3.one;
//設定下劃線文本的初始值
underlineText.text = "_";
//單個下劃線寬度
float singleUnderlineWidth = underlineText.preferredWidth;
//文本總寬度
float targetTextWidth = targetText.preferredWidth;
//計算需要多少個“_”字元
int underlineCount = Mathf.RoundToInt(targetTextWidth / singleUnderlineWidth);
//添加“_”字元
for (int i = 0; i < underlineCount; i++)
{
underlineText.text += "_";
}
}
}
完成的效果如下:
注意事項
上面代碼實作簡單,但有局限性和不足之處:
1.該代碼隻适合為确定的文本添加下劃線,如果在程式運作過程中,文本内容實時變動,此代碼不适用。後續我會繼續研究實作動态更新下劃線的方法。
2. 如果要為文本元件TextA添加下劃線,切記,腳本TextUnderLine一定不要添加到TextA遊戲物體上,因為這樣會造成邏輯上的死循環,建立出無數個下劃線子物體。