Search code examples
unity-game-engineunity3d-gui

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


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 :)


Solution

  • 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);
                                                         });
    }