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
EasyGive the meadow game a menu: write Start() in Menu.cs.
- Hide
menuPanelandhelpPanelwithSetActive(false). menuButtonshows the menu and setsmover.enabled = false;resumeButtonhides it and setsmover.enabled = true.helpButtonhides the menu and shows the help;backButtondoes 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
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 SwapPractice on your own: Unity playground