Unity两组Toggle一一对应关系

发布时间:2024年01月09日
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Crosscorrelation : MonoBehaviour
{
    public Toggle[] leftToggles;
    public Toggle[] rightToggles;
    private int lastClickedToggleIndex = -1;
    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < leftToggles.Length; i++)
        {
            int index = i;
            leftToggles[i].onValueChanged.AddListener(isOn =>)
        }
    }
    private void HandleToggleChanged(int index, bool isOn, bool isLeftToggle)
    {
        if (isOn)
        {
            lastClickedToggleIndex = index;
            SyncToggles(index, isLeftToggle);

        }
        else
        {
            SetToggleState(index, false, isLeftToggle); // 当一个Toggle被设置为false时,同步关闭另一个Toggle
            lastClickedToggleIndex = -1;
        }
        CommonToggleChangedHandler(index);
    }



    private void SyncToggles(int index, bool isLeftToggle)
    {
        //设置当前组Toggle状态
        SetToggleState(index, true, isLeftToggle);
        //重置其他所有Toggles
        for (int i = 0; i < leftToggles.Length; i++)
        {
            if (i != index)
            {
                SetToggleState(i, false, true); // 关闭其他所有Toggles
            }
        }

    }
    private void SetToggleState(int index, bool isOn, bool isLeftToggle)
    {
        if (isLeftToggle)
        {
            leftToggles[index].isOn = isOn;
            rightToggles[index].isOn = isOn;
        }
        else
        {
            rightToggles[index].isOn = isOn;
            leftToggles[index].isOn = isOn;
        }
    }

    private void CommonToggleChangedHandler(int index)
    {
        Debug.Log("执行共同方法");
    }
    // Update is called once per frame
    void Update()
    {

    }
}

用于点击一按钮另一按钮也执行,同时在Toggle组里只有当前点击的toggle为true,其他为false

文章来源:https://blog.csdn.net/weixin_44047050/article/details/135477071
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。