Skip to content

Instantly share code, notes, and snippets.

@xrdnk
Last active Nov 1, 2021
Embed
What would you like to do?
TextMeshPro のテキストに URL 文字列が存在する時,ハイパーリンク化する
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;
}
}
}
@xrdnk
Copy link
Author

xrdnk commented Oct 31, 2021

TextMeshPro のテキストに URL 文字列が存在する時,ハイパーリンク化する - デニッキ!
https://xrdnk.hateblo.jp/entry/2021/10/31/121518

@xrdnk
Copy link
Author

xrdnk commented Nov 1, 2021

マッチした箇所が重複している場合も考慮し,修正

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment