每一个Toggle都对应一个页面


当切换isOn时显示对应的页面


using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[RequireComponent(typeof(ToggleGroup))]
public class SwitchView : MonoBehaviour {

    [System.Serializable]
    public struct Relation
    {
        public Toggle toggle;
        public Transform root;
    }

    public Relation[] roots;

    public class SwitchEvent : UnityEvent<int>{ }
    public SwitchEvent onSwitch = new SwitchEvent();

    private void Awake()
    {
        var toggleGroup = GetComponent<ToggleGroup>();
        for (int i = 0; i < roots.Length; i++)
        {
            var x = i;
            var toggle = roots[i].toggle;
            toggle.group = toggleGroup;
            toggle.isOn = true;
            toggle.onValueChanged.AddListener(isOn => {
                onSwitch.Invoke(x);
                roots[x].root.gameObject.SetActive(isOn);
            });
            toggle.isOn = false;
        }
        roots[0].toggle.isOn = true;
    }
}


更多推荐