Unity组件Toggle详解
1.首先先搭建UI(如下图)
2.如果实现单选的功能需要在Image上面挂载ToggleGroup脚本组件
2.2 选中三个Toggle把ToggleGroup拖到如下图位置即可
2.AllowSwitchOff 默认是不勾选的就是单选状态 (运行选中其中一个Toggle其他两个Toggle会取消选中,自己测试即可)
2.1 勾选允许出现都不勾选的情况。不勾选有且只有一个被勾选,运行测试有一个会被勾选上
3.下面是代码动态绑定方法简单介绍一下代码如下
using LitJson; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class NewDisease : MonoBehaviour { public Toggle[] toggles; // Start is called before the first frame update void Start() { //第一种 toggles[0].onValueChanged.AddListener(delegate { if (toggles[0].isOn) { Debug.Log("开启"); } else { Debug.Log("关闭"); } }); //第二种 //toggles[0].onValueChanged.AddListener(ToggleDebug); //第三种 多个参数 toggles[0].onValueChanged.AddListener((ison)=> { ToggleDebug(0, ison); }); } public void ToggleDebug(bool value) { if (value) { Debug.Log("开启"); } else { Debug.Log("关闭"); } } public void ToggleDebug(int index,bool value) { if (value) { Debug.Log("开启" +index); } else { Debug.Log("关闭"+ index); } } }
4.第四种 添加toggle方法
drawSelects[0].onValueChanged.AddListener(delegate (bool bol)
简单记录一下,要不然容易忘记,如果喜欢就加个关注吧,谢谢