原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1014/81.html
今天我们常州游戏设计培训工作室幻天网络要分享的是UGUI中文本下划线的实现,在Unity5.2.2版本之前,UGUI富文本是不支持下划线的,下面就自己封装一个简单的,可当链接点击跳转。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LinkButton : MonoBehaviour {
private Text linkText;
void Awake()
{
linkText = transform.Find("Text").GetComponent<Text>();
}
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<Button>();
btn.onClick.AddListener(onClickBtn);
}
//点击响应
void onButtonClick()
{
Debug.Log("onClick");
}
}
UGUI文本下划线实现原理就是在原Text上加了一个内容是下划线的Text。
UGUI文本下划线实现原理就是在原Text上加了一个内容是下划线的Text。
上篇:上一篇:U3D场景切换时背景音乐不间断播放
下篇:下一篇:Unity3d框架-UI管理类 UIManager