Menu
CoddyTech

Panels On and Off

Part of the Building Real Games section of Coddy's Unity journey. Lesson 9 of 60.

A panel is a UI Image, often stretched over the whole screen, with buttons and texts as its children. SetActive(false) on the panel hides it with everything inside, and its buttons cannot be clicked while it is hidden. While it is shown, its image takes the clicks meant for anything under it, so the buttons behind a full-screen panel cannot be pressed. This map opens from a button in the corner and closes from a button on the map:

public GameObject mapPanel;
public Button mapButton;
public Button closeButton;

void Start()
{
    mapPanel.SetActive(false);
    mapButton.onClick.AddListener(() => mapPanel.SetActive(true));
    closeButton.onClick.AddListener(() => mapPanel.SetActive(false));
}

Panels are easier to edit while they show, so scenes are often saved with them on, and Start() hides them. Keep the script that opens a panel off that panel: an inactive GameObject gets no Start() or Update(), so a script on a panel saved hidden would never hook up its buttons. The Canvas or a game manager object, which stay active, are good homes for it. mapPanel.activeSelf tells whether the panel is on, so mapPanel.SetActive(!mapPanel.activeSelf) flips it.

challenge icon

Challenge

Easy

Give the meadow game a menu: write Start() in Menu.cs.

  1. Hide menuPanel and helpPanel with SetActive(false).
  2. menuButton shows the menu and sets mover.enabled = false; resumeButton hides it and sets mover.enabled = true.
  3. helpButton hides the menu and shows the help; backButton does the opposite.

Press Play and open the menu: the player cannot walk until Resume. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;

public class Menu : MonoBehaviour
{
    public GameObject menuPanel;
    public GameObject helpPanel;
    public Button menuButton;
    public Button resumeButton;
    public Button helpButton;
    public Button backButton;
    public PlayerMover mover;

    void Start()
    {
        // Hide both panels, then hook up Menu, Resume, Help and Back
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground