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")) {
		
	}
}

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
}

merci

j’avais déjà essayé avec l’active mais j’ai dû ma planter qqpart, ca buggait.

Thanks for this thread, script works fine!.