UGUI中的文本添加链接下划线并跳转

来源:互联网 发布:淘宝买家举证 编辑:程序博客网 时间:2024/06/05 04:36

哈哈,想了很久,试了好几种方法,最后还是自己写一下

先看代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class BtnTest : MonoBehaviour {
    public Button btnselect;//不用在意这是测试的委托代码
    public Text linkText;
    void Awake()
    {
        linkText = GameObject.Find("Canvas").transform.Find("Text").GetComponent<Text>();


    }
    void Start()
    {
        CreateLink(linkText);
        //给按钮绑定事件
        ButtonEvent.Get(btnselect.transform).clickObj += selectOnClick;
        // ButtonEvent.Get(textlint.transform).clickObj += onclick;
    }  


    void selectOnClick()
    {


        Debug.Log("Test is Sucess");
       
    }
  public  void onclick()
    {
        Application.OpenURL("www.baidu.com");
    }
    //创建下划线
  public void CreateLink(Text text)
  {
      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;
      
      int lineCount = (int)Mathf.Round(width / perlineWidth);
   
      for (int i = 1; i < lineCount; i++)
      {
          underline.text += "_";
      }
  }  
}


不足之处请大家多多指教

原创粉丝点击