78 lines
2.4 KiB
C#
78 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
using UnityEngine.EventSystems;
|
|
|
|
[RequireComponent(typeof(TMP_Text))]
|
|
public class LinkText : MonoBehaviour, IPointerClickHandler
|
|
{
|
|
List<UnityAction> ClickAction;
|
|
|
|
UnityAction otherAreaClickAction;
|
|
|
|
public void SetLinkAction(List<UnityAction> unityActions)
|
|
{
|
|
ClickAction = unityActions;
|
|
}
|
|
public void SetOtherAreaClicked(UnityAction callback)
|
|
{
|
|
otherAreaClickAction = callback;
|
|
}
|
|
|
|
public void OnPointerClick(PointerEventData eventData)
|
|
{
|
|
DebugUtil.Log("OnPointerClick called.");
|
|
TMP_Text pTextMeshPro = GetComponent<TMP_Text>();
|
|
|
|
int linkIndex =
|
|
TMP_TextUtilities.FindIntersectingLink(pTextMeshPro, eventData.position, eventData.pressEventCamera);
|
|
// If you are not in a Canvas using Screen Overlay, put your camera instead of null
|
|
|
|
if (linkIndex != -1)
|
|
{
|
|
TMP_LinkInfo linkInfo = pTextMeshPro.textInfo.linkInfo[linkIndex];
|
|
DebugUtil.Log("OnPointerClick called.");
|
|
DebugUtil.Log("Link ID: \"" + linkInfo.GetLinkID() + "\" Link Text: \"" + linkInfo.GetLinkText());
|
|
//Application.OpenURL(linkInfo.GetLinkID());
|
|
|
|
if (ClickAction != null && linkIndex < ClickAction.Count)
|
|
{
|
|
ClickAction[linkIndex]();
|
|
}
|
|
else
|
|
{
|
|
DebugUtil.LogError("Link index out of range.");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
otherAreaClickAction?.Invoke();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设置含超链接跳转<link>的文本
|
|
/// </summary>
|
|
/// <param name="text"></param>
|
|
public void SetText(string text)
|
|
{
|
|
TMP_Text pTextMeshPro = GetComponent<TMP_Text>();
|
|
pTextMeshPro.text = text;
|
|
|
|
string pattern = "<link=\"(.*?)\">(.*?)</link>";
|
|
System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(text, pattern);
|
|
|
|
List<UnityAction> LinkActions = new();
|
|
foreach (System.Text.RegularExpressions.Match match in matches)
|
|
{
|
|
string linkID = match.Groups[1].Value;
|
|
string linkText = match.Groups[2].Value;
|
|
|
|
LinkActions.Add(() => Application.OpenURL(linkID));
|
|
}
|
|
SetLinkAction(LinkActions);
|
|
}
|
|
}
|