- Home /
Toggle gameobject on/off with button
Hi, I've been trying to toggle a gameobject on and off with a button but keep getting errors like..
"No appropriate version of 'UnityEngine.GUI.Button' for the argument list '(UnityEngine.Rect, boolean, String)' was found".
Here is my current code, can anyone help?
var icon : Texture2D;
var toggleBool = true;
var target : GameObject;
function OnGUI () {
GUI.Box (Rect (0,0,100,90), "Top-left");
toggleBool = GUI.Button (Rect (10,30,90,20), toggleBool, "turn on/off");
target.SetActive(toggleBool);
}
Answer by Baste · Oct 01, 2014 at 07:31 AM
That's not how GUI.Button works - no version takes a bool argument. Check out the docs.
You need to do something like
if(GUI.Button(Rect (10,30,90,20), "turn on/off"))
toggleBool = !toggleBool
target.SetActive(toggleBool);
toggleBool = !toggleBool then we need a ; to close it down :)
Answer by Jan Rabe · Dec 02, 2015 at 06:42 PM
or:
gameObject.SetActive(!gameObject.activeInHierarchy);
Answer by corbinyo · May 30, 2019 at 11:41 PM
A method like this will work:
public GameObject GameObjectToHide;
void Start()
{
GameObjectToHide = GameObject.FindGameObjectWithTag("GameObjectToHide");
}
public void HideGameObject()
{
if
(GameObjectToHide.activeInHierarchy)
{
GameObjectToHide.SetActive(false);
}
else
{
GameObjectToHide.SetActive(true);
}
}
Your answer
Follow this Question
Related Questions
GameObject as a toggle button to play character Animation 1 Answer
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
How to basically use GUI.Toggle? 2 Answers
How many times awake function is called when toggle on/off gameObjects with the same C# script 1 Answer
Game Object Toggle GUI Button Errors 1 Answer