Unity 4.6+: How to disable/enable GUI panel with a UI button by script

Acidon picture Acidon · Aug 13, 2015 · Viewed 7.9k times · Source

I am just starting with unity and having problems to show/hide menu panel with a button click.

I am using unity 5 and able to do it by playing On Click() button parameter right in the inspector:

I click "+", drag my panel in object field, and the select GameObject > SetActive(Bool) function.

However what I am looking to learn is the way to achieve similar behavior with C# script. I tried:

using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.Events;
 using System.Collections;

 public class closebutton : MonoBehaviour {

     public GameObject menu;

     void OnMouseDown() {
         menu.SetActive(false);
     }

 }

but nothing happens...

Please help me to achieve this basic task :)

Answer

Reasurria picture Reasurria · Aug 13, 2015

The way you are already doing it is better (in inspector with onClick).

If you are just curious then you can do the following:

void Start()
{
    GetComponent<Button>().onClick.AddListener(() => {
                                                         menu.SetActive(false);
                                                     });
}