- Home /
Use a toggle button to change a GameObjects visibility
I need to be able to turn the visibility of a Game Object on and off using a toggle button. This is the code I have currently:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ShowSubway : MonoBehaviour {
public GameObject subway;
public void showSubway(){
if(gameObject.tag == "subway"){
subway.gameObject.SetActive (true);
}
}
public void hideSubway(){
if(gameObject.tag == "subway"){
subway.gameObject.SetActive (false);
}
}
}
Could anyone help please?
Answer by Hellium · Apr 16, 2018 at 12:13 PM
You don't need this script.
Just select your toggle, add a new entry in the OnValueChanged
event, drag & drop the object you want, and select GameObject > SetActive
(dynamic parameter)
I read the question too fast and didn't realize it was a toggle, and not a button ;)
Answer by Koyemsi · Apr 16, 2018 at 12:38 PM
Hi, you can do this :
1- Attach this script to any GameObject you want. Don't forget to fill the subway
field in the inspector.
public class ShowSubway : MonoBehaviour {
public GameObject subway;
public void ToggleSubway () {
subway.SetActive (!subway.activeInHierarchy);
}
}
Note : As subway
was declared as a GameObject
, you don't need to write subway.gameobject
to set it active.
2- On your button script, on the OnClick event, put a reference to the game object that contains your script, and call its method ShowSubway.ToggleSubway()
.
You should be good to go.
Your answer
Follow this Question
Related Questions
how to use itween with the object attached to other moving object 0 Answers
Do Something ONLY when all Toggles are On or Off 4 Answers
HUD reticle question 0 Answers
[c#] first script isnt disabling canvas and player cant move (issue with first script) 0 Answers
How to make UI checkbox appear or disappear in start function? 1 Answer