Files
Studio/Assets/Scripts/UVC/UI/UVCButton.cs
2025-05-20 18:29:36 +09:00

132 lines
3.8 KiB
C#

using System;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Studio.UVC.UI
{
[RequireComponent(typeof(RectTransform))]
public class UVCButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
private static GameObject prefab;
public static UVCButton Create(string text, Transform parent = null)
{
if (prefab == null) prefab = Resources.Load("Prefabs/Common/UVCButton", typeof(GameObject)) as GameObject;
var instance = Instantiate(prefab, parent);
var btn = instance.GetComponent<UVCButton>();
if (text != null && text.Length > 0) btn.GetComponentInChildren<TextMeshProUGUI>().text = text;
return btn;
}
[SerializeField]
private bool selected = false;
public bool Selected { get => selected; }
public int Index { get; set; }
private TextMeshProUGUI txt;
private UnityEngine.UI.Button button;
public Button UVCClickButton { get { return button; } }
private RectTransform rect;
public RectTransform Rect { get { return rect; } }
private Image image;
public Image Image { get { return image; } }
public float Space = 8f;
[Header("Color")]
public Color normalColor;
public Color HighLightColor;
public Color selectColor;
[Header("Sprite")]
public Sprite normalSprite;
public Sprite selectSprite;
public UnityEvent onClickButton;
public void Init()
{
txt = GetComponentInChildren<TextMeshProUGUI>();
button = GetComponent<UnityEngine.UI.Button>();
rect = GetComponent<RectTransform>();
image = GetComponent<Image>();
button.navigation = new Navigation() { mode = Navigation.Mode.None };
if (button != null)
{
button.onClick.AddListener(() =>
{
if (selected) return;
selected = true;
onClickButton.Invoke();
});
}
}
/// <summary>
/// 텍스트 길이에 따른 사이즈 변경
/// </summary>
/// <param name="text">Title Name</param>
public void SetText(string text)
{
txt.text = text;
rect.sizeDelta = new Vector2(txt.preferredWidth + Space, rect.sizeDelta.y);
}
/// <summary>
/// 선택된 탭
/// </summary>
public void Select()
{
if (image == null) image = GetComponent<Image>();
if (txt == null) txt = GetComponentInChildren<TextMeshProUGUI>();
image.sprite = selectSprite;
image.color = selectColor;
selected = true;
}
/// <summary>
/// 탭이 변경 될 경우
/// </summary>
public void Deselect()
{
if (image == null) image = GetComponent<Image>();
if (txt == null) txt = GetComponentInChildren<TextMeshProUGUI>();
image.sprite = normalSprite;
image.color = normalColor;
selected = false;
}
private void OnDestroy()
{
if (button != null) button.onClick.RemoveAllListeners();
onClickButton.RemoveAllListeners();
}
public void OnPointerEnter(PointerEventData eventData)
{
image.sprite = selectSprite;
image.color = HighLightColor;
}
public void OnPointerExit(PointerEventData eventData)
{
if (selected)
image.color = selectColor;
else
image.sprite = normalSprite;
image.color = normalColor;
}
}
}