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
EasyThe 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,
menuPanelandhelpPanelare hidden. menuButtonopens the menu panel, and itsresumeButtoncloses it.helpButton, on the menu panel, swaps the menu panel for the help panel, andbackButton, on the help panel, swaps back.- While the menu is open the player cannot walk: the
moverscript 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap