Files
AppleHillsProduction/Assets/Scripts/UI/CardSystem/BookTabButton.cs
2025-11-06 01:25:13 +01:00

129 lines
3.8 KiB
C#

using System;
using BookCurlPro;
using UnityEngine;
using UnityEngine.UI;
using Tween = Pixelplacement.Tween;
namespace UI.CardSystem
{
/// <summary>
/// Tab button for navigating to specific pages in the card album book.
/// Coordinates with other tabs via static events for visual feedback.
/// </summary>
[RequireComponent(typeof(Button))]
public class BookTabButton : MonoBehaviour
{
[Header("Book Reference")]
[SerializeField] private BookPro book;
[Header("Tab Configuration")]
[SerializeField] private int targetPage;
[Header("Visual Settings")]
[SerializeField] private bool enableScaling = true;
[SerializeField] private float selectedScale = 2.0f;
[SerializeField] private float normalScale = 1.0f;
[SerializeField] private float scaleTransitionDuration = 0.2f;
private Button button;
private RectTransform rectTransform;
private Vector2 originalSize;
// Static dispatcher for coordinating all tabs
private static event Action<BookTabButton> OnTabClicked;
private void Awake()
{
// Get required components
button = GetComponent<Button>();
rectTransform = GetComponent<RectTransform>();
// Cache original size
originalSize = rectTransform.sizeDelta;
// Register button click
button.onClick.AddListener(OnButtonClicked);
// Subscribe to static tab event
OnTabClicked += OnAnyTabClicked;
}
private void OnDestroy()
{
// Cleanup listeners
if (button != null)
{
button.onClick.RemoveListener(OnButtonClicked);
}
OnTabClicked -= OnAnyTabClicked;
}
private void OnButtonClicked()
{
if (book == null)
{
Debug.LogWarning($"[BookTabButton] No BookPro reference assigned on {gameObject.name}");
return;
}
// Notify all tabs that this one was clicked
OnTabClicked?.Invoke(this);
// Flip to target page using AutoFlip
BookCurlPro.AutoFlip autoFlip = book.GetComponent<BookCurlPro.AutoFlip>();
if (autoFlip == null)
{
autoFlip = book.gameObject.AddComponent<BookCurlPro.AutoFlip>();
}
autoFlip.enabled = true;
autoFlip.StartFlipping(targetPage);
}
private void OnAnyTabClicked(BookTabButton clickedTab)
{
// Skip scaling if disabled
if (!enableScaling) return;
// Scale this tab based on whether it was clicked
if (clickedTab == this)
{
SetScale(selectedScale);
}
else
{
SetScale(normalScale);
}
}
private void SetScale(float targetScale)
{
Vector2 targetSize = originalSize * targetScale;
// Use Pixelplacement Tween for smooth size change
Tween.Value(rectTransform.sizeDelta, targetSize,
(Vector2 value) => rectTransform.sizeDelta = value,
scaleTransitionDuration, 0f, Tween.EaseInOut);
}
// Public method to programmatically trigger this tab
public void ActivateTab()
{
OnButtonClicked();
}
#if UNITY_EDITOR
private void OnValidate()
{
// Ensure target page is non-negative
if (targetPage < 0)
{
targetPage = 0;
}
}
#endif
}
}