Files
Studio/Assets/Scripts/XED/UI/Panel/Panel_Tooltip.cs
2025-02-21 11:57:09 +09:00

98 lines
2.6 KiB
C#

using System.Reflection;
using System.Xml;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.UI.Extensions;
using XRLib.UI;
namespace XED.UI
{
public class Panel_Tooltip : PanelBase
{
RectTransform image_bg;
TextMeshProUGUI text_tooltip;
public Vector2 padding = new Vector2(20f, 10f);
public override void AfterAwake()
{
transform.SetAsLastSibling();
}
public void ActivateTooltip(RaycastResult hit)
{
if (hit.gameObject.GetComponent<UI_TooltipOwner>() == null)
return;
text_tooltip.text = GetTooltip(hit);
UpdateBackgroundSize();
MoveToMousePos();
gameObject.SetActive(true);
}
string GetTooltip(RaycastResult hit)
{
string tooltipText = "None";
var propertyViewerInfo = hit.gameObject.GetComponent<UI_PropertyViewerInfo>();
if (propertyViewerInfo != null)
{
var tooltipAttr = propertyViewerInfo.fieldInfo.GetCustomAttribute<TooltipAttribute>();
if (tooltipAttr != null)
{
tooltipText = tooltipAttr.tooltip;
}
}
else
{
UI_TooltipOwner tooltipOwner = hit.gameObject.GetComponent<UI_TooltipOwner>();
tooltipText = tooltipOwner.tooltipText;
}
return tooltipText;
}
public void DeactivateTooltip()
{
gameObject.SetActive(false);
}
void UpdateBackgroundSize()
{
float textWidth = text_tooltip.preferredWidth;
float textHeight = text_tooltip.preferredHeight;
image_bg.sizeDelta = new Vector2(textWidth + padding.x, textHeight + padding.y);
}
void MoveToMousePos()
{
Vector2 mousePos = Input.mousePosition;
float bgSizeX = image_bg.sizeDelta.x / 2;
float bgSizeY = image_bg.sizeDelta.y / 2;
float movePosX = mousePos.x + bgSizeX;
float movePosY = mousePos.y - bgSizeY;
if (mousePos.x + image_bg.sizeDelta.x > Screen.width)
{
movePosX = mousePos.x - bgSizeX;
}
if (mousePos.y - image_bg.sizeDelta.y < 0)
{
movePosY = mousePos.y + bgSizeY;
}
Vector2 movePos = new Vector2(movePosX, movePosY);
image_bg.transform.position = movePos;
text_tooltip.transform.position = movePos;
}
}
}