Controlling visibility of several objects with GUI


This is my first attempt at coding with javascript in Unity and I’ve run into difficulty with what I think should be a relatively simple task.

I have three objects in the scene and I want to control their visibility using three GUI buttons, one for each object. I need it to work so that each button makes an object visible while making the other two invisible.

I have so far got the following script attached to my scene camera:

function OnGUI () {

if (GUI.Button (Rect (20,40,80,20), "Blue")) {
name = "Sphere-Blue";renderer.enabled = true;
name = "Sphere-Red";renderer.enabled = false;
name = "Sphere-Green";renderer.enabled = false;


Using this I am not getting the behaviour I had hoped for. Ideally, the button named “Blue” would make the “Sphere-Blue” object visible while blocking out the other objects.

Am I even close? Searching the forums has got me to this point but I’m feeling pretty lost now.

Any help would be greatly appreciated.

Kind Regards


Yes, “Sphere-Blue” “Sphere-Green” and “Sphere-Red” are the names of the objects I have in the scene, though I’m not sure about the renderer? I haven’t attached any renderers, I’m not even sure what that means.

Add this script:

#pragma strict

// Define a button setting data structure
public class ButtonSwitch
	public var name 		: String; // Name of GUI button
	public var renderer		: Renderer; // Reference to actual 3D object
	public var areaOnScreen	: Rect; // Rectangle to place GUI button

public var buttonAction : ButtonSwitch[]; // An array of all button settings

function OnGUI () 
	var buttonSwitchedIndex : int = -1;

    // Process all button settings
	for(var b=0; b<buttonAction.Length; b++)
            // Draw button with current settings. Check if a button with current settings was click. 
		if ( GUI.Button(buttonAction__.areaOnScreen, buttonAction**.name) )**__

** {**
// Show 3D object
__ buttonAction**.renderer.enabled = true;
// Remember the place in array of the pressed button**
** buttonSwitchedIndex = b;

** // Shutdown the rest of the buttons**
** if ( buttonSwitchedIndex > -1 )**
** {**
** for(b=0; b<buttonAction.Length; b++)**
** {**
// Unless this is the 3D button we showed, hide button
** if ( buttonSwitchedIndex != b )**
__ buttonAction**.renderer.enabled = false;

1. Attach it to a new game object.
2. You have a list of “Button Action” - set it to “3” as you have 3 button.
3. Set the name of each of the buttons as you wish to appear on the button label.
4. Into the “renderer” field - drag the obrect corresponding to that button, e.g. to the “Blue” drag the object “Sphere-Blue”.
5. “Area On Screen” is the rect you set to place the GUI button.
Now, clicking on the gui button should do the trick.
Renderer is the component that draws a 3D object in your game.__