我正在做一个统一的项目。情况是,我有两个切换按钮(实际上是两个以上)toggle1和toggle2以及两个游戏对象cube1和cube2。在开始时,两个切换都未选中,游戏对象为SetActive(false)。我想要的是两个按钮都按toggle1.isOn && toggle2.isOn然后cube1 SetActive,如果按切换顺序,即toggle2.isOn && toggle1.isOn然后cube2 SetActive,则首先选择哪个切换。 现在的问题是,当我选中toggle1然后按顺序显示两个多维数据集时,当我选中toggle2然后按触发1时,两个多维数据集又都出现了...。
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ToggleToggle : MonoBehaviour {
public Toggle toggle1;
public Toggle toggle2;
public GameObject cube;
public GameObject cube2;
// Use this for initialization
void Start () {
cube.SetActive (false);
cube2.SetActive (false);
}
// Update is called once per frame
void Update () {
// Toggle1 Selected First then Toggle2
if (toggle1.isOn && toggle2.isOn) {
cube.SetActive (true);
}
// Toggle2 Selected First then Toggle1
if (toggle2.isOn && toggle1.isOn) {
cube2.SetActive (true);
}
}
}
答案 0 :(得分:0)
程序中的错误是您忘记通知按下的第一个按钮:
public int first;
void Start () {
cube.SetActive (false);
cube2.SetActive (false);
first = 0;
}
// Update is called once per frame
void Update () {
if (!toggle1.isOn && !toggle2.isOn) {
first = 0;
}
if (first == 0 && toggle1.isOn) {
first = 1;
}
if (first == 0 && toggle2.isOn) {
first = 2;
}
if (first == 1 && toggle2.isOn) {
cube.SetActive (true);
}
if (first == 2 && toggle1.isOn) {
cube2.SetActive (true);
}
}
答案 1 :(得分:0)
据我所知,您只想基于多个GameObject
启用一个 Toggle
。
勾选的第一个将确定哪个GameObject
。
因此,您必须存储第一个被选中的Toggle
。
这里是一个例子:
public class ToggleToggle : MonoBehaviour {
/*
public Toggle toggle1;
public Toggle toggle2;
public GameObject cube;
public GameObject cube2;
*/
public Toggle[] toggles;
public GameObject[] cubes;
public static Toggle firstTickedToggle;
void Start ()
{
for (int i = 0; i < cubes.Length; i++)
{
cubes[i].SetActive(false);
}
}
public void OnToggleClick(Toggle toggle)
{
if (toggle.enabled)
{
if (firstTickedToggle == null)
firstTickedToggle = toggle;
int toggleIndex = 0; // Index of the first clicked toggle
// Check if all toggles are ticked
for (int i = 0; i < toggles.Length; i++)
{
// If one is not ticked
if (!toggles[i].enabled)
return;
if (toggles[i] == firstTickedToggle)
toggleIndex = i;
}
// Here all toggles are ticked
cubes[toggleIndex].SetActive(true);
}
else
{
for (int i = 0; i < toggles.Length; i++)
{
// If one toggle is still ticked, don't do anything
if (toggles[i].enabled)
return;
}
// If all toggles are unticked, remove the reference to the first ticked
firstTickedToggle = null;
}
}
}