- Home /
how to toggle on/off a gameobject with a GUI button ?
Hello,
I would like to be able to toggle on and off an object by clicking on a button.
I would like it to be generic, so I can assign it to any object I want and when I click on one button, I hide the objet and when I click on another button, I make it visible again.
What kind of function do I need to create to toggle on and off an object ?
I would like to use javascript for it and I just have the basic code :
// JavaScript
var icon : Texture2D;
var toggleBool = true;
var target : GameObject;
var target2 : GameObject;
function OnGUI () {
GUI.Box (Rect (0,0,100,90), "Top-left");
if (GUI.Button (Rect (10,30,80,20), "turn on")) {
}
if (GUI.Button (Rect (10,60,80,20), "turn off")) {
}
}
Answer by aldonaletto · Jan 25, 2013 at 11:48 AM
If you just want to make the object invisible, set renderer.enabled to false. If you want to deactivate the object, use gameObject.SetActive(false). Your code could be something like this:
var icon : Texture2D;
var toggleBool = true;
var target : GameObject;
var target2 : GameObject;
function OnGUI () {
GUI.Box (Rect (0,0,100,90), "Top-left");
if (GUI.Button (Rect (10,30,80,20), "turn on")) {
target.SetActive(true);
}
if (GUI.Button (Rect (10,60,80,20), "turn off")) {
target.SetActive(false);
}
}
You could also use a single Toggle button instead of two buttons:
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);
// or target.renderer.enabled = toggleBool; for just making it visible or not
}
Cool, thanks. I was wondering what if I wanted to make the object turn red on toggle?
You can change the renderer material color.
target.renderer.material.color = Color.red;
That theoretically works but I'm running into this problem: http://answers.unity3d.com/questions/639169/changing-gameobject-material-color-makes-object-di.html
Answer by earar · Jan 25, 2013 at 01:17 PM
merci
j'avais déjà essayé avec l'active mais j'ai dû ma planter qqpart, ca buggait.
Your answer
Follow this Question
Related Questions
Detect Click on Gameobject 0 Answers
How do I make individual buttons change individual variables? 0 Answers
Cube click pop-up menu 0 Answers
Using GUI and check what button was pressed 1 Answer
GameObject touchable instead GUI button 3 Answers