TH1/Unity/Assets/Scripts/TH1_UI/Common/TribeHoverEffect.cs
2025-09-08 02:49:12 +08:00

117 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using TH1_Core.Managers;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class TribeHoverEffect : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
private Image maskImage;
private Button button;
private GameObject _tribeDiagBG;
private bool isSelected = false;
private Color highlightColor = new Color32(38, 93, 175, 255);
private Color defaultColor = new Color32(0x2A, 0xFF, 0x00, 255); // #2AFF00
private byte normalAlpha = 150;
private byte hoverAlpha = 200;
private byte selectedAlpha = 255;
public bool IsLocked;
void Awake()
{
// 自动获取 UI 组件
maskImage = transform.Find("TribeIconMask/Mask")?.GetComponent<Image>();
_tribeDiagBG = transform.Find("TribeIconMask/TribeDiagBG")?.gameObject;
// 获取同节点的 Button
button = GetComponent<Button>();
}
void Start()
{
// 如果有 Button则通过代码绑定点击事件
if (button != null)
{
button.onClick.RemoveAllListeners();
button.onClick.AddListener(HandleButtonClick);
}
}
// 供 Button 调用的封装
public void HandleButtonClick()
{
if(!IsLocked)
OnClicked();
}
private void OnClicked()
{
// 取消兄弟节点选中
Transform parent = transform.parent;
if (parent != null)
{
foreach (Transform child in parent)
{
if (child == transform) continue;
var effect = child.GetComponent<TribeHoverEffect>();
if (effect != null)
{
effect.Deselect();
}
}
}
// 自身设为选中
isSelected = true;
SetAlpha(maskImage, selectedAlpha);
_tribeDiagBG?.SetActive(true);
}
public void OnPointerEnter(PointerEventData eventData)
{
if (IsLocked) return;
if (!isSelected)
{
SetAlpha(maskImage, hoverAlpha);
}
}
public void OnPointerExit(PointerEventData eventData)
{
if (IsLocked) return;
if (!isSelected)
{
SetAlpha(maskImage, normalAlpha);
}
}
private void ApplyNormalState()
{
SetAlpha(maskImage, normalAlpha);
_tribeDiagBG?.SetActive(false);
}
private void SetAlpha(Image image, byte alpha)
{
if (image == null) return;
Color color = image.color;
color.a = alpha / 255f;
image.color = color;
}
public void Deselect()
{
isSelected = false;
ApplyNormalState();
_tribeDiagBG?.SetActive(false);
}
public bool CheckIsSelected()
{
return isSelected;
}
}