当前位置: 代码迷 >> 综合 >> UGUI 超链接文字脚本
  详细解决方案

UGUI 超链接文字脚本

热度:27   发布时间:2023-12-15 17:26:28.0

using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.Globalization;

/// <summary>
/// 超链接类型
/// </summary>
public enum HyperlinkType
{
    Url = 0,//超链接url

    Task = 1,//任务

    Null,//下划线
}

/// <summary>
/// 下划线可点击文字
/// 19.07.04 by Rocketjie
/// </summary>
public class UnderLineScript : MonoBehaviour
{
    [Tooltip("Hyperlink type")]
    public HyperlinkType type = HyperlinkType.Null;

    [Tooltip("Hyperlink url")]
    public string HyperlinkUrl = "";

    private Text text;
    private Button btn;

    public void Awake()
    {
        text = gameObject.GetComponent<Text>();
    }

    public void Start()
    {
        if (text != null)
        {
            Text under_line = Instantiate(text) as Text;
            Destroy(under_line.transform.GetComponent<UnderLineScript>());
            under_line.transform.SetParent(text.transform);

            RectTransform rt = under_line.rectTransform;
            rt.anchoredPosition3D = Vector3.zero;
            rt.offsetMax = Vector2.zero;
            rt.offsetMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.anchorMin = Vector2.zero;

            under_line.text = "_";
            int line_count = (int)Mathf.Round(text.preferredWidth / under_line.preferredWidth);
            for (int i = 1; i < line_count; i++)
            {
                under_line.text += "_";
            }

            btn = gameObject.AddComponent<Button>();
            btn.onClick.AddListener(OnClick);
        }
    }

    private void OnClick()
    {
        switch(type)
        {
            case HyperlinkType.Url:
                OpenWebUrl();
                break;
            case HyperlinkType.Task:
                DoTask();
                break;
            case HyperlinkType.Null:
                break;
        }
    }

    /// <summary>
    /// 打开网页
    /// </summary>
    private void OpenWebUrl()
    {
        string strHttp = "http";
        CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo;
        if (Compare.IndexOf(HyperlinkUrl, strHttp, CompareOptions.IgnoreCase) != -1)
        {
            WWW www = new WWW(HyperlinkUrl);
            if (string.IsNullOrEmpty(www.error))
            {
                Application.OpenURL(www.url);
            }
            else
            {
                Logger.LogError("url is error .. : " + www.url);
            }
        }
    }

    /// <summary>
    /// 执行任务
    /// </summary>
    private void DoTask()
    {
        Logger.LogError("do task");
    }
}