Unity 通用标签页切换管理器
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.Events;
[System.Serializable]
public class TabEvent : UnityEvent<int> { }
public class TabManager : MonoBehaviour
{
[Tooltip("存放所有标签按钮的父物体")]
public Transform tabButtonsParent;
[Tooltip("存放所有标签内容的父物体")]
public Transform tabContentsParent;
[Tooltip("默认选中的标签索引")]
public int defaultTabIndex = 0;
[Tooltip("标签切换事件")]
public TabEvent TabChanged;
private List<Button> tabButtons = new List<Button>();
private List<GameObject> tabContents = new List<GameObject>();
private int currentTabIndex = -1;
private void Awake()
{
// 获取所有标签按钮
if (tabButtonsParent != null)
{
foreach (Transform child in tabButtonsParent)
{
Button button = child.GetComponent<Button>();
if (button != null)
{
tabButtons.Add(button);
}
}
}
// 获取所有标签内容
if (tabContentsParent != null)
{
foreach (Transform child in tabContentsParent)
{
tabContents.Add(child.gameObject);
}
}
// 验证标签按钮和内容数量是否一致
if (tabButtons.Count != tabContents.Count)
{
Debug.LogError($"标签按钮数量({tabButtons.Count})与标签内容数量({tabContents.Count})不一致!");
}
// 注册按钮点击事件
for (int i = 0; i < tabButtons.Count; i++)
{
int index = i;
tabButtons[i].onClick.AddListener(() => OnTabButtonClicked(index));
}
}
private void Start()
{
// 自动选中默认标签(如果启用)
if (tabButtons.Count > 0)
{
if (defaultTabIndex >= 0 && defaultTabIndex < tabButtons.Count && tabButtons[defaultTabIndex].gameObject.activeSelf)
{
SelectTab(defaultTabIndex);
}
else
{
// 找第一个可用标签
for (int i = 0; i < tabButtons.Count; i++)
{
if (tabButtons[i].gameObject.activeSelf)
{
SelectTab(i);
break;
}
}
}
}
}
/// <summary>
/// 标签按钮点击事件
/// </summary>
private void OnTabButtonClicked(int index)
{
if (index != currentTabIndex && index >= 0 && index < tabButtons.Count)
{
SelectTab(index);
}
}
/// <summary>
/// 选中指定标签
/// </summary>
public void SelectTab(int index)
{
if (index < 0 || index >= tabButtons.Count)
{
Debug.LogError($"无效的标签索引: {index}");
return;
}
// 更新之前选中的标签状态
if (currentTabIndex != -1 && currentTabIndex < tabButtons.Count)
{
tabButtons[currentTabIndex].interactable = true; // 之前的按钮恢复可点击
tabContents[currentTabIndex].SetActive(false);
}
// 更新当前选中的标签状态
currentTabIndex = index;
tabButtons[currentTabIndex].interactable = false; // 当前按钮禁用点击
tabContents[currentTabIndex].SetActive(true);
// 触发标签切换事件
TabChanged?.Invoke(currentTabIndex);
}
/// <summary>
/// 获取当前选中的标签索引
/// </summary>
public int GetCurrentTabIndex()
{
return currentTabIndex;
}
/// <summary>
/// 设置指定标签的启用状态
/// </summary>
public void SetTabEnabled(int index, bool enabled)
{
if (index >= 0 && index < tabButtons.Count)
{
// 如果要禁用当前选中的标签,自动切换到第一个可用标签
if (!enabled && index == currentTabIndex)
{
for (int i = 0; i < tabButtons.Count; i++)
{
if (i != index && tabButtons[i].gameObject.activeSelf)
{
SelectTab(i);
break;
}
}
}
tabButtons[index].gameObject.SetActive(enabled);
tabContents[index].SetActive(enabled); // 同步隐藏内容
}
}
}
版权申明
本文系作者 @xiin 原创发布在To Future$站点。未经许可,禁止转载。
暂无评论数据