- Home /
How do you make one object disappear and another appear with one button press?
I am making a 2D flashcard game where you are shown a word and you can press buttons to change it to a different language. Each button (there are three) toggles on and off a word but these words occupy the same space and overlap each other. What i want to happen is when i click on one button to toggle on a word the other words are toggled off.
This is what i have so far. I have this script attached to each button.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class WordOpener : MonoBehaviour { public GameObject haochin; public GameObject haopin; public GameObject good;
public void OpenHaochin()
{
if (haochin != null)
{
bool isActive = haochin.activeSelf;
haochin.SetActive(!isActive);
}
}
public void OpenHaopin()
{
if (haopin != null)
{
bool isActive = haopin.activeSelf;
haopin.SetActive(!isActive);
}
}
public void OpenGood()
{
if (good != null)
{
bool isActive = good.activeSelf;
good.SetActive(!isActive);
}
}
}
I haven't found anything online that i could get to work. Any ideas?
If you have three toggles, why not having them in a Toggle Group
(see doc ) and drag & drop the appropriate gameObject in the onValueChanged
event & select GameObject > SetActive
(in the dynamic category)?
Answer by Skyppex_ · Jul 23, 2021 at 07:58 PM
When you click the button you need to identify which one you would like to be active and activate is and then deactivate all the other ones in the same method. Although this doesn't scale well.
a simple solution would be:
public void OpenHaochin()
{
if (haochin != null)
{
haochin.SetActive(true);
haopin.SetActive(false);
good.SetActive(false);
}
}
public void OpenHaopin()
{
if (haopin != null)
{
haopin.SetActive(true);
haochin.SetActive(false);
good.SetActive(false);
}
}
public void OpenGood()
{
if (good != null)
{
good.SetActive(true);
haopin.SetActive(false);
haochin.SetActive(false);
}
}
if you want to have more words later you could add them all to a list and loop through them.
//Assign the words in the list through the editor like you did with the individual objects
[SerializedField] private List<GameObject> words = new List<GameObject>();
public void OpenWord(string wordName)
{
foreach (GameObject word in words)
{
if (word.name == wordName)
{
word.SetActive(true);
return;
}
word.SetActive(false);
}
//This code is only reached if the loop never finds a valid word to set to active meaning something went wrong
Debug.Error("Word name: " + wordName + " does not exist");
}
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Trouble with Unity2d Text 0 Answers
Changing player's moving direction 0 Answers
How to have two of the same UI Text? 1 Answer