Hệ thống Tooltip đơn giản cho UI
C# Code
/* TooltipManager.cs (Singleton) */
using UnityEngine;
using TMPro;
public class TooltipManager : MonoBehaviour
{
public static TooltipManager Instance { get; private set; }
public Tooltip tooltip;
void Awake()
{
if (Instance != null && Instance != this) Destroy(gameObject); else Instance = this;
}
void Start()
{
if (tooltip != null) tooltip.gameObject.SetActive(false);
}
public void ShowTooltip(string content)
{
if (tooltip != null)
{
tooltip.SetText(content);
tooltip.gameObject.SetActive(true);
}
}
public void HideTooltip()
{
if (tooltip != null) tooltip.gameObject.SetActive(false);
}
}
/* Tooltip.cs */
using UnityEngine;
using TMPro;
public class Tooltip : MonoBehaviour
{
public TextMeshProUGUI contentField;
public RectTransform backgroundRectTransform;
private RectTransform rectTransform;
void Awake()
{
rectTransform = GetComponent<RectTransform>();
}
void Update()
{
// Follow mouse position
transform.position = Input.mousePosition;
// Adjust pivot to stay on screen
Vector2 pivot = new Vector2(Input.mousePosition.x / Screen.width, Input.mousePosition.y / Screen.height > 0.5f ? 1 : 0);
rectTransform.pivot = pivot;
}
public void SetText(string content)
{
contentField.text = content;
// Optional: Adjust background size based on text length
backgroundRectTransform.sizeDelta = new Vector2(contentField.preferredWidth + 20f, contentField.preferredHeight + 20f);
}
}
/* TooltipTrigger.cs */
using UnityEngine;
using UnityEngine.EventSystems;
public class TooltipTrigger : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[TextArea]
public string content;
public void OnPointerEnter(PointerEventData eventData)
{
TooltipManager.Instance.ShowTooltip(content);
}
public void OnPointerExit(PointerEventData eventData)
{
TooltipManager.Instance.HideTooltip();
}
}Hiển thị một khung thông tin (tooltip) khi người dùng di chuột qua một đối tượng UI. Gồm 3 scripts: TooltipTrigger để kích hoạt, Tooltip để hiển thị, và TooltipManager (Singleton) để quản lý.