- Home /
Button Turns Off and On Object
I've successfully created a code to turn off an object when a button is pressed. That being said I want to be able to press the button again to turn the object back on. (possible even to change color to indicate when it is on or off)
Unfortunately when I press the button the object disappears (which is good) but the button disappears too (which is bad) . what can I add to my script to accomplish the above. Thanks for your help :) using UnityEngine; using System.Collections;
public class ButtonGuiScript : MonoBehaviour {
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
private void OnGUI()
{
if(GUI.Button(new Rect(15, 15, 100, 50), "West Wind Zone"))
{
gameObject.SetActive(false);
}
}
}
Answer by NoseKills · Nov 15, 2014 at 11:18 AM
or just
cube.SetActive(!cube.gameObject.activeSelf);
depending on whether you prefer shorter code or less variables
Answer by Kiwasi · Nov 15, 2014 at 03:13 AM
Standard way to do this is
bool isOn;
private void OnGUI(){
if(GUI.Button(new Rect(15, 15, 100, 50), "West Wind Zone")){
isOn = !isOn;
gameObject.SetActive(isOn);
}
}
Thanks for the response! I think my mistake is that I've attached the script directly to the game object that I want to vanish. When it vanishes the button disappears as well. How can I create a button to refer to the cube without being a script attached to the cube itself?
I'm reasonably new to unity and my scripting skills are rough. Would I write a script and attach it to another object and reference the cube this way?
var cube:"TameObject" ##name of the gameObject I'm referencing
That's close. It would be something like:
public GameObject cube;
private bool active;
private void OnGUI(){
if(GUI.Button(new Rect(15, 15, 100, 50), "West Wind Zone")){
active = !active;
cube.SetActive(active);
}
}
And then you'd attach it to some object that will stay active, such as the main camera. After that, just drag in the cube from the Hierarchy to the Inspector to the "Cube" slot.
@JSierraA$$anonymous$$A$$anonymous$$C's code will do the trick.
@soulpiper12 You've used the JavaScript syntax in your comments, where your question was in C#. Trying to mix the two will only cause trouble. Note that var is generally a JavaScript term. It means something different in C# and is seldom used.