vrijdag 18 maart 2016

Canvas Groups

While making UI for a game, I stumbled upon something I didn't know about. Lets say you have a pause screen and in-game UI. When you pause the game, you want the in-game UI to disappear and the menu to show up. Well there is an easy way to achieve that very effect.

Canvas Groups

When making UI with Unity's canvas system, you have the option to put every UI element in the canvas. But there is also a trick you can do to make canvas groups. Groups with UI elements in it. If you create an Empty GameObject and add the Canvas Group component to it. This is now treated as a Canvas Group. These canvas groups can then be manipulated through code. For example, hide the in-game UI when the game is paused and vice versa.

It is actually very easy to manipulate these through code. Make two public references for CanvasGroups and give them appropriate names.
 public CanvasGroup inGame;
 public CanvasGroup pause;
There are four properties of the Canvas Group you can edit.

  • Alpha - Value between 0 and 1, where 0 is invisible and 1 visible
  • Interactable - Boolean for it's interactabilty. When it is set to false interaction is disabled.
  • Block Raycasts - Will this component act as a collider for Raycasts? When set to true it is interacting with Raycasts.
  • Ignore Parent Groups - Will this group also be affected by the settings in Canvas Group components further up in the Game Object hierarchy, or will it ignore those and hence override them?


 When the game is paused I want the pause menu to show up and the in-game menu to disappear. So when the Pause button is pressed, you set the in-game's alpha to 0, making it invisible and its blockraycasts property to false, because I worked with raycasts. You can also set the 'interactable' property to false here. For the pause canvas group you do the exact opposite. You set the pause alpha to 1 and the block raycasts to true. It's maybe a bit confusing to set 'block raycasts' to true for it to NOT block raycasts, but that's how it is. For the play button you do the opposite to make the in-game UI appear again.
 if (Input.GetKeyDown("Pause")
        {
  inGame.alpha = 0;
  inGame.blocksRaycasts = false;
 
  pause.alpha = 1;
  pause.blocksRaycasts = true;
 }
 if (Input.GetKeyDown("Play")
        {
  inGame.alpha = 1;
  inGame.blocksRaycasts = true;
 
  pause.alpha = 0;
  pause.blocksRaycasts = false;
 }

Geen opmerkingen:

Een reactie posten