Last active
November 1, 2021 09:39
-
-
Save xrdnk/9c43724274f81500cd6edfcbaa434b24 to your computer and use it in GitHub Desktop.
TextMeshPro のテキストに URL 文字列が存在する時,ハイパーリンク化する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text.RegularExpressions; | |
using TMPro; | |
using UnityEngine; | |
using UnityEngine.EventSystems; | |
namespace Denicode | |
{ | |
public sealed class HyperLinkExample : MonoBehaviour, IPointerDownHandler | |
{ | |
[SerializeField, TextArea] string _message = "Google\nhttps://www.google.co.jp/\nApple\nhttps://www.apple.com/"; | |
[SerializeField] TextMeshProUGUI _textMessage = null; | |
void Awake() | |
{ | |
SetMessage(_message); | |
} | |
void SetMessage(string message) | |
{ | |
_textMessage.text = message.AddHyperLink().AddNewLine(); | |
} | |
public void OnPointerDown(PointerEventData eventData) | |
{ | |
var pos = Input.mousePosition; | |
var canvas = _textMessage.canvas; | |
var targetCamera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera; | |
var index = TMP_TextUtilities.FindIntersectingLink(_textMessage, pos, targetCamera); | |
if (index == -1) | |
{ | |
return; | |
} | |
var linkInfo = _textMessage.textInfo.linkInfo[index]; | |
var url = linkInfo.GetLinkID(); | |
Application.OpenURL(url); | |
} | |
} | |
public static class StringExtensions | |
{ | |
const string URL_REGEX_PATTERN = @"https?://[\w!\?/\+\-_~=;\.,\*&@#\$%\(\)'\[\]]+"; | |
const string HYPER_LINK_TAG = "<color=#00ACBF><u><link=\"{0}\">{0}</link></u></color>"; | |
const string NEW_LINE_PATTERN = @"\n"; | |
/// <summary> | |
/// 文字にURL文字列が存在する時,タグを付与する | |
/// </summary> | |
public static string AddHyperLink(this string message) | |
{ | |
var newMessage = message; | |
var matches = Regex.Matches(newMessage, URL_REGEX_PATTERN); | |
var matchValues = (from Match match in matches select match.Value).ToList(); | |
// マッチした箇所が重複している場合は取り除く(取り除かないと何重にも置換されて表記がおかしくなる) | |
foreach (var value in matchValues.Distinct()) | |
{ | |
newMessage = newMessage.Replace(value, string.Format(HYPER_LINK_TAG, value)); | |
} | |
return newMessage; | |
} | |
/// <summary> | |
/// 文字に改行コードが存在する時,改行する | |
/// </summary> | |
public static string AddNewLine(this string message) | |
{ | |
var newMessage = message; | |
if (newMessage.Contains(NEW_LINE_PATTERN)) | |
{ | |
newMessage = newMessage.Replace(NEW_LINE_PATTERN, Environment.NewLine); | |
} | |
return newMessage; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TextMeshPro のテキストに URL 文字列が存在する時,ハイパーリンク化する - デニッキ!
https://xrdnk.hateblo.jp/entry/2021/10/31/121518