Files
JJBB/Assets/Project/Script/GUI/Rank/TogglesControl.cs
2024-08-23 15:49:34 +08:00

81 lines
2.2 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 UnityEngine;
using System.Collections;
using UnityEngine.UI;
// 用于控制一组 UIToggleSwap
public class TogglesControl : MonoBehaviour {
private ToggleGroup toggleGroup; // 控制唯一 Toggle 被勾选
private Toggle[] toggles; // 子物体 toggles
private UIToggleSwap[] toggleSwaps; // toggles 显示脚本
public delegate void VoidIntDelegate(int index);
public event VoidIntDelegate OnTogglesSelect; // 返回当前被选中的 Toggle 索引
private bool hasInit = false;
private void Awake()
{
Init();
}
private void Init()
{
if (!hasInit)
{
toggleGroup = transform.GetComponent<ToggleGroup>();
toggles = transform.GetComponentsInChildren<Toggle>();
toggleSwaps = transform.GetComponentsInChildren<UIToggleSwap>();
for (int i = 0; i < toggles.Length; ++i)
{
toggles[i].group = toggleGroup;
toggles[i].onValueChanged.AddListener(OnToggleChange);
toggles[i].onValueChanged.AddListener(toggleSwaps[i].OnToggleSwap);
}
hasInit = true;
}
}
/// <summary>
/// 设置ToggleS组中某个Toggle成激活状态
/// </summary>
/// <param name="index">激活的的Toggle索引0为第一个</param>
public void SetToggleOn(int index = 0)
{
// 此处Init为解决当其他脚本在OnEnable调用时该脚本会出现未初始化的情况。
Init();
if(toggles != null && index != -1)
{
if(index < toggles.Length)
{
toggles[index].isOn = true;
}
}
}
public void OnToggleChange(bool isOn)
{
if(isOn)
{
for(int i = 0; i < toggles.Length; i++)
{
if(toggles[i].isOn && OnTogglesSelect != null)
{
OnTogglesSelect(i);
break;
}
}
}
}
public void OnDisable()
{
foreach (Toggle tg in toggles)
{
tg.isOn = false;
}
}
}