Reputation: 25
I am making a unity project. The situation is that I have two toggle buttons (actually more than two) toggle1 and toggle2 and two gameobjects cube1 and cube2. On start both the toggles are unchecked and gameobjects are SetActive(false). What I want is if both buttons toggle1.isOn && toggle2.isOn then cube1 SetActive and if toggle2.isOn && toggle1.isOn then cube2 SetActive according to toggle orders i.e. which toggle is selected first. Now the problem is that When I Checked toggle1 then toggle2 in order both cubes appears and when I Checked toggle2 then toggle1 then again both cubes appears....
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);
}
}
}
Upvotes: 1
Views: 1097
Reputation: 270
If I understand well, you want to enable only one GameObject
based on multiple Toggle
s.
The first ticked determines which GameObject
.
So you have to store the first ticked Toggle
.
Here is an example :
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;
}
}
}
All toggles need a OnValueChanged
Upvotes: 0
Reputation: 17007
The error in your program is you forget to notify the first button pressed:
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);
}
}
Upvotes: 0