AkiraPixelWind/Assets/Scripts/Main/UI/UIYYControl/UILinkButton.cs
2022-12-29 18:20:40 +08:00

71 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/// <summary>
/// 超链接按钮 参考资料 [1] 陌的专栏 http://blog.csdn.net/juan_bo/article/details/52301302
/// </summary>
public class UILinkButton : MonoBehaviour
{
private Text linkText;
public string m_url;
void Awake()
{
var tfText = transform.Find("Text");
if (tfText)
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;
underline.transform.localScale = Vector3.one;
//设置下划线坐标和位置
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; //单个下划线宽度
float width = text.preferredWidth;
int lineCount = (int)Mathf.Round(width / perlineWidth);
for (int i = 1; i < lineCount; i++)
underline.text += "_";
var btn = text.gameObject.AddComponent<UIButton>();
btn.onClick.AddListener(onClickBtn);
}
//点击响应
void onButtonClick()
{
if (string.IsNullOrEmpty(m_url))
return;
Application.OpenURL(m_url);
}
}