Menu
CoddyTech

Panels On and Off

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

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

The meadow game needs a menu. Menu.cs sits on the Canvas (HUD), and the scene links its fields. Both panels are on in the scene, so they are easy to edit. Write Start() so that:

  • When the game starts, menuPanel and helpPanel are hidden.
  • menuButton opens the menu panel, and its resumeButton closes it.
  • helpButton, on the menu panel, swaps the menu panel for the help panel, and backButton, on the help panel, swaps back.
  • While the menu is open the player cannot walk: the mover script is disabled when the menu opens and enabled again when Resume closes it.

Press Play, walk, open the menu and its help, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games