how to make my gameobjects disable and enable?

Hi all, i have two game objects in my project. i want to show only one in the scene. i wrote code like this.

 using UnityEngine;
 using System.Collections;

 public class Moon : MonoBehaviour {

public bool onoff;
public Texture2D icon;
public GameObject table;
public GameObject moon;
// Use this for initialization
void Start () {

// Update is called once per frame
void Update () {

	 if (onoff == true) = true; = false;
     if (onoff == false) = true; = false;
void OnGUI () {
	GUI.Button (new Rect (10,10,100,50), icon);


my intention is i want to show any one by default. if the user click that icon i want to show second one and first becomes turn off. if he again clicks i want first one. like that i want to show.

but i add and run this code by default i didn’t get the any one. i add all the things in the inspector view.

please help me.

thank you


You use “if” without the braces, but there’s 2 instructions.

A if without braces but must be followed by only one instruction. In :

 if (onoff == true) = true; = false;
     if (onoff == false) = true; = false;

Your “ = false” and “ = false” are out the if and will be called every frame.
Try with braces.

Other things : You button is not correct. Try with this :

 if(GUI.Button (new Rect (10,10,100,50), icon))

The GUI.Button must be into an if statement. Because GUI.Button return a boolean which indicate if yes or no you push the button. So i guess for your problem :

table active is always false cause out the if.
onoff = true in OnGUI is automaticly called because no if statement.
so on the update, = true is called, but = false is out the if, so neither table nor moon will be active.


PS : Prog tips, you don’t need to write “if(onoff == true)”, just “if(onoff)”. Idem for negative comparaison “if(onoff == false)” becomes “if(!onoff)”. :slight_smile:

Dude there is have methods for hide object on any event from the scene
gameObject.SetActive (boolean); //this will active or deactivate your object from the scene

gameObject.renderer.enabled = boolean; //this will enable/desable your object mesh