86 lines
3.0 KiB
C#
86 lines
3.0 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using System.Collections;
|
|
|
|
public class DebugUIMessage : MonoBehaviour
|
|
{
|
|
private static DebugUIMessage instance;
|
|
private Text messageText;
|
|
private Canvas canvas;
|
|
private Coroutine hideCoroutine;
|
|
|
|
/// <summary>
|
|
/// Show a debug message on the UI for a set duration.
|
|
/// </summary>
|
|
/// <param name="message">The message to display.</param>
|
|
/// <param name="duration">How long to display the message (seconds).</param>
|
|
/// <param name="displayColor"></param>
|
|
public static void Show(string message, Color displayColor, float duration = 2f)
|
|
{
|
|
if (instance == null)
|
|
{
|
|
var go = new GameObject("DebugUIMessage");
|
|
instance = go.AddComponent<DebugUIMessage>();
|
|
instance.SetupUI();
|
|
DontDestroyOnLoad(go);
|
|
}
|
|
instance.ShowMessage(message, duration, displayColor);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets up the UI canvas and text for debug messages.
|
|
/// </summary>
|
|
private void SetupUI()
|
|
{
|
|
canvas = new GameObject("DebugUICanvas").AddComponent<Canvas>();
|
|
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
|
|
canvas.sortingOrder = 9999;
|
|
canvas.gameObject.transform.SetParent(transform);
|
|
var textGO = new GameObject("DebugUIText");
|
|
textGO.transform.SetParent(canvas.transform);
|
|
messageText = textGO.AddComponent<Text>();
|
|
messageText.alignment = TextAnchor.MiddleCenter;
|
|
// Try to load a custom font from Resources/Fonts/DebugFont.ttf
|
|
Font customFont = Resources.Load<Font>("Fonts/DebugFont");
|
|
if (customFont != null)
|
|
messageText.font = customFont;
|
|
else
|
|
messageText.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
|
|
messageText.fontSize = 32;
|
|
messageText.color = Color.yellow;
|
|
var outline = textGO.AddComponent<Outline>();
|
|
outline.effectColor = Color.black;
|
|
outline.effectDistance = new Vector2(2, -2);
|
|
var rect = messageText.GetComponent<RectTransform>();
|
|
rect.anchorMin = new Vector2(0.5f, 0.5f);
|
|
rect.anchorMax = new Vector2(0.5f, 0.5f);
|
|
rect.pivot = new Vector2(0.5f, 0.5f);
|
|
rect.anchoredPosition = Vector2.zero;
|
|
rect.sizeDelta = new Vector2(800, 40);
|
|
messageText.text = "";
|
|
}
|
|
|
|
/// <summary>
|
|
/// Internal method to show a message and start the hide coroutine.
|
|
/// </summary>
|
|
private void ShowMessage(string message, float duration, Color fontColor)
|
|
{
|
|
messageText.text = message;
|
|
messageText.color = fontColor;
|
|
messageText.enabled = true;
|
|
if (hideCoroutine != null)
|
|
StopCoroutine(hideCoroutine);
|
|
hideCoroutine = StartCoroutine(HideAfterSeconds(duration));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Coroutine to hide the message after a delay.
|
|
/// </summary>
|
|
private IEnumerator HideAfterSeconds(float seconds)
|
|
{
|
|
yield return new WaitForSeconds(seconds);
|
|
messageText.text = "";
|
|
messageText.enabled = false;
|
|
}
|
|
}
|