ProjectDDD/Assets/_DDD/_Scripts/GameUi/New/TabGroupUi.cs

67 lines
1.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace DDD
{
public class TabGroupUi<T> : MonoBehaviour where T : Enum
{
[SerializeField] private List<TabButtonUi<T>> _tabButtons;
private Dictionary<T, TabButtonUi<T>> _tabLookup;
private Action<T> _onTabSelected;
public T CurrentTab { get; private set; }
public List<T> TabOrder => _tabButtons.ConvertAll(b => b.TabType);
public GameObject GetFirstInteractableButton =>
_tabButtons.FirstOrDefault(b => b.ButtonIsInteractable)?.ButtonGameObject;
public void Initialize(Action<T> onTabSelected)
{
_onTabSelected = onTabSelected;
_tabLookup = new Dictionary<T, TabButtonUi<T>>();
foreach (var tab in _tabButtons)
{
tab.Initialize(OnTabClicked);
_tabLookup[tab.TabType] = tab;
}
if (_tabButtons.Count > 0)
{
SelectTab(_tabButtons[0].TabType);
}
}
private void OnTabClicked(T type)
{
SelectTab(type);
}
public void SelectTab(T type)
{
CurrentTab = type;
foreach (var tab in _tabButtons)
{
tab.SetSelected(tab.TabType.Equals(type));
}
_onTabSelected?.Invoke(type);
}
public void Move(int direction)
{
var tabTypes = TabOrder;
int index = tabTypes.IndexOf(CurrentTab);
int count = tabTypes.Count;
if (count == 0) return;
int newIndex = (index + direction + count) % count;
SelectTab(tabTypes[newIndex]);
}
}
}