February 28, 2019
Tower Defense Tutorial
Episode 21 – Pause Menu
Youtube – How to make a Tower Defense Game (E21 PAUSE MENU) – Unity Tutorial
By: Brackeys
Ep. 21
This tutorial focused on creating the Pause Menu.
To start, we create another UI Panel as the base for the pause menu, and added buttons for: Continue, Retry and Menu. This also had text saying “Paused”.
We created a new script on our Game Manager, PauseMenu. This would deal with the functionality of activating/deactivating our pause menu UI elements. This was done with a method called Toggle, which used a command of ui.SetActive(!ui.activeSelf) which would set whether it was enabled or not to the opposite of what it currently is.
We then got to actually pausing the game. This can be done by simply setting Time.timeScale = 0f. It is commonly mistaken that you also need to set Time.fixedDeltaTime to 0 as well, but this is actually taken care of by Time.timeScale already. We also need to unpause, so we set Time.timeScale back to 1f when that is needed.
It is important to note that while Time.timeScale is at 0, this does prevent some things from working. The hover color of UI buttons was still fine as it is not affected by the timescale, but animations you are running with the Animator will be. They need a specific setting changed in order to function properly. This was shown by trying to fade in our pause menu. Initially, we created a simple recorded animation of changing the alpha from 0 to 1, but when we ran it in game it did not appear. That is because the animation was frozen with the timeScale.
To prevent the animation from being affected by our timescale variation, we change the “Update Mode” in the Animator component of the object we are animating from Normal to Unscaled Time.
Then, we also wanted to animate the buttons some (instead of just having a simple highlight color). To start, we went to the Button (script) component and changed the Transition to Animation. We then selected AutoGenerate Animation. This gave us 4 options in the Animation tab for: Normal, Highlighted, Pressed, Disabled. These are the 4 states of the button. These let you set an animation to start whenever these separate events occur.
SUMMARY
- Use [gameObject].SetActive(![gameObject].activeSelf) to inverse the current enabled state of a gameObject
- Use Time.timeScale = 0f; to do a simple pause of your game. This should also set Time.fixedDeltaTime to 0f behind the scenes so you do not need to set this as well. (To unpause, set Time.timeScale back to 1f.)
- If you want to animate objects during timescale = 0 (like pause menu animations), make sure to change their Animator component Update Modes from Normal to Unscaled Time.
- To animate UI buttons, select Animation for Transition under the Button (script) component (built into Unity UI buttons). Can then select AutoGenerate animation to record animations like anything else, and for all 4 different states of the button (Normal, Highlighted, Pressed, Disabled).