Hiding and showing the Canvas

We have decided that the UI in our game will be made up of three simple views:

  • MenuView
  • InGameView
  • GameOverView

We have created most of the MenuView. I am using two terms here, View and Canvas. In our simple game, both of them will mean the same thing. MenuCanvas is just the visible part of MenuView. Keep that in mind.

The simplest way to toggle the view's visibility is by enabling and disabling the Canvas component. Let's test how it works without the code for now:

  1. Press Play in Unity.
  2. Select the MenuCanvas game object in the Hierarchy window.
  3. Disable the Canvas element, marked here:
    Hiding and showing the Canvas
  4. As the Canvas component is responsible for rendering the UI in the scene, disabling it will hide the content of all UI elements within the canvas.

    Note

    Note once again that disabling the Canvas component will hide all UI elements within the canvas. It will also disable all events handled by the Event System.

It's been a while since we wrote some code. Let's implement the same behavior in the code. Add a Canvas type public member to the GameManager class and call it menuCanvas. We will use this reference in GameManager for easy access:

public Canvas menuCanvas;

Edit SetGameState by adding three lines that enable and disable the Canvas component, as follows:

Hiding and showing the Canvas

Well done! We have a piece of basic code that is enabling and disabling the Canvas for us.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset