UGUI 文本下划线实现

UGUI富文本好像没有支持下划线(到5.2.2),自己封装了一个简单的,可当链接点击跳转。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LinkButton : MonoBehaviour {

    private Text linkText;

    void Awake()
    {
        linkText = transform.Find("Text").GetComponent();

    }
	void Start () 
    {
        CreateLink(linkText, onButtonClick);
	}

    public void CreateLink(Text text,UnityEngine.Events.UnityAction onClickBtn)
    {
        if (text == null)
            return;

        //克隆Text,获得相同的属性
        Text underline = Instantiate(text) as Text;
        underline.name = "Underline";

        underline.transform.SetParent(text.transform);
        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 = "_";
        float perlineWidth = underline.preferredWidth;      //单个下划线宽度
        Debug.Log(perlineWidth);

        float width = text.preferredWidth;
        Debug.Log(width);
        int lineCount = (int)Mathf.Round(width / perlineWidth);
        Debug.Log(lineCount);
        for(int i = 1;i < lineCount;i++)
        {
            underline.text += "_";
        }

        var btn = text.gameObject.AddComponent
原理就是在原Text上加了一个内容是下划线的Text。
效果图: UGUI 文本下划线实现_第1张图片

你可能感兴趣的:(unity3d,界面)