Unity2D: Adding A Game Over Screen
I added a game over screen in my current project by disabling and enabling canvases.
I have a UI Manager that is attached to the player itself. This game object holds 2 canvases; PlayerUI and GameOverCanvas.
PlayerUI will disable and GameOverCanvas will enable when the player dies. To simulate, ’Changing Screens’.
The Game Over Canvas
They’re 3 texts in total with two of them having button functionality. The Restart Text And Quit Text contain button components within them. They both have the Scene Manager prefab attached to their Onclick() events which will allow them to access a function that will load a scene.
I only have two scenes available at the moment. My main menu is on the scene index of 0 and my game scene on 1. So I pass the appropriate integer according to what I want to load.
For my restart button I pass 1 to reload my game scene or ,’Restarting’ it. Quit will be assigned 0 to go back to the title screen.
When the Player Dies
I have a boolean named ,’PlayerIsDead’ that is within a static class called ,’Player Values’.
When the player is dead, this boolean will become true. When playerIsDead is set to true, a chain of events occur.
if the player has died from taking too much damage, then this property will set PlayerIsDead to false. Then it will disable the collider and sprite render.
I chose not to destroy the game object because the UI is attached to the game object. Destroying it will also destroy the UI.
My UI Manager(At the moment) constantly checks if the player is dead in update.
Here is where the canvases will swap.
Note: since my PlayerIsDead boolean is declared within a static class. It will contain the same value it was last given until the application has been closed.
Meaning, if I reload the scene. PlayerIsDead will still remain True.
To fix this, I make sure I reset all values whenever the player initially instantiates.
Now I can restart and quit the game without any issues