Jump to content
  • Advertisement
  • entries
    44
  • comments
    19
  • views
    2424

Day 22 of 100 Days of VR: Creating the Game End State and Game Over Animation

Josh Chang

702 views

Hi and welcome back to day 22 of the 100 days of VR!

Yesterday, we created our game over panel to show to the player when they lose, however in the current state of the game, the game over panel is being displayed at the start of the game.

Today, we’re going to:

  1. Create a new state controller for our animation so that we don’t instantly play our animation
  2. Play the animation when the player is defeated and all states related to that
  3. Restart the game when the player selects to play again

There’s a lot ahead of us today, so let’s get started!

Creating an Animation State Controller

Right now, our animation just plays whenever the game starts.

The reason for that is, because of our animator controller.

Go to our GameOver.controller in the Animation folder and double click it to open it up in our Animator tab.

 
0*z0i_mO5cF64pjudU.png

Right now, Game Over is the default state we transition into from Entry.

As a result, we always play the Game Over clip that’s attached to it be default when we start our game.

To fix this, we’re going to do a couple of things. We’re going to:

  1. create a new default state,called Start that is our default transition from Entry that transitions into our Game Over state
  2. create a new boolean parameter IsGameOver
  3. set a transition from Start to Game Over
  4. select the transition arrow from Start to Game Over and create a new condition: IsGameOver = true

After you’re done, you should have something like this:

 
0*5FqEr7ymDA25kT3i.png

Now if we’re to play our game again, nothing will show up!

Playing the Game Over animation

Now that we have the correct game states set up, it’s time to use it.

All we need to do is play the animation when our player’s health drops to 0.

Here are the changes we’re going to do:

  1. Create a new GameManager script that will take care of the logic of the ending
  2. Change our PlayerHealth script to use the GameManager to tell it when the game is over.

The first thing we’re going to do is create an empty game object that we’ll call GameManager.

Then create a new script called GameManager and attach it to our new game object.

Here’s what our GameManager script will look like:

 
using UnityEngine;
public class GameManager : MonoBehaviour
{
    public Animator GameOverAnimator;
    public void GameOver()
    {
        GameOverAnimator.SetBool("IsGameOver", true);
    }
}
 

The code right now is straightforward:

  1. We get the GameOverAnimator from our Game Over object and we take the Animator from it.
  2. We create a public GameOver() that someone will call that will set our IsGameOver parameter to be true so that we’ll play the animation to show our game over panel.

When you’re done with the script, make sure to set our GameOver UI GameObject to our GameOverAnimator slot in our GameManagercomponent.

Quick note on pushing vs pulling for updates

For those of you who saw Unity’s tutorial, I’m not actually a big fan of what Unity does with having all of these checks in the Update(), where we’re always checking for something to happen.

Personally, I much prefer to take a more push functionality where we only do something, if something else notifies us of it happening.

A perfect example of a push approach is our public GameOver(). Currently we have some other script call the function to indicated game over.

An example of pulling is that we have a script that checks for changes every frame. For example. We could have given GameManager a reference the the player Game Object and in Update() it could constantly check to see if the player is dead.

Both way works, I just prefer the way where we only do something when we’re told to do it and not check every frame.

Using our GameManager

After creating our GameManger, we need to use it.

In this particular case, we’re going to use it in our PlayerHealth script. We’re going to:

  1. Add our GameManager object
  2. Call GameOver() when the player’s health is 0 or below

Here’s our code:

 
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
    public Slider HealthBar;
    public float Health = 100;
    private float _currentHealth;
    private GameManager _gameManager;
    void Start ()
    {
        _currentHealth = Health;
        _gameManager = Object.FindObjectOfType<GameManager>();
    }
    public void TakeDamage(float damage)
    {
        _currentHealth -= damage;
        HealthBar.value = _currentHealth;
        if (_currentHealth <= 0)
        {
            _gameManager.GameOver();
        } 
    }
}
 

The code here is also straightforward:

  1. We create a private field for our GameManager class
  2. In Start() we instantiate our GameManager
  3. In TakeDamage(), after our player takes damage and health falls to 0, we would call GameOver() which will show the Game Over panel.

Restarting the Game

Now that we have our game over panel showing up, it’s time for us to disable some functionality so that we can click on the restart button!

There’s a couple of things we need to:

  1. in GameManager, when GameOver() is called disable the player’s movements and re-enable our cursor to select a button
  2. create a GameOverUIManager that will deal with the logic of clicking a button
  3. change our GameOver game object’s Canvas Group to ignore parent elements and check the Blocks Raycasts option so we can click on the button

Updating GameManager to Disable the Player in Game Over

When the game is over, we want to:

  • disable all the scripts that are involved with the controls of the player. It would be weird that at game over we can still move around and shoot.
  • re-enable our Cursor which we locked in the center of the game

Here are the changes we did to GameManager:

 
using UnityEngine;
public class GameManager : MonoBehaviour
{
    public Animator GameOverAnimator;
    private GameObject _player;
    void Start()
    {
        _player = GameObject.FindGameObjectWithTag("Player");
    }
    public void GameOver()
    {
        GameOverAnimator.SetBool("IsGameOver", true);
        _player.GetComponent<PlayerController>().enabled = false;
        _player.GetComponentInChildren<MouseCameraContoller>().enabled = false;
        _player.GetComponentInChildren<PlayerShootingController>().enabled = false;
        Cursor.lockState = CursorLockMode.None;
    }
}
 

As you can see, we:

  1. Created a reference to our player character in Start()
  2. In GameOver() we disabled the player movement script, our mouse script, and our shooting script. We also re-enabled our lock

With this, if you were to play the game right now and let our player die, we regain our mouse and we won’t be able to control our player anymore.

 
0*Py9582hVtm-nCfza.png

Creating the Code for our UI Button Click

Next, we need some code to take care of what happens when we click on our button.

To do that we need to create a onClick event listener for our button.

For those of use that aren’t familiar with the concept of event listeners, you can think of it as code that will only execute when you take a certain action.

In this specific instance, our Button has a onClick event listener so it’ll wait for whenever the user clicks on the button.

When someone does click the button, they’ll execute any function that was passed to it. In this case, our restart code.

Let’s get started.

First, create a new script for our GameOver game object in the hierarchy. We’re going to call it GameOverUIManager. We’re going to use it to manage our play the game when the user clicks play again.

Here’s what it looks like:

 
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameOverUIManager : MonoBehaviour
{
    private Button _button;
    void Start () {
        _button = GetComponentInChildren<Button>();
        _button.onClick.AddListener(ClickPlayAgain);
    }
    public void ClickPlayAgain()
    {
        SceneManager.LoadScene("Main");
    } 
}
 

Now let’s walk through the code:

  1. We have a private _button that is the button from our Game Over Panel.
  2. In Start() we instantiate our button and we set the OnClick Listener to our button to run ClickPlayAgain() whenever the user clicks the button
  3. In ClickPlayAgain(), we use the SceneManager to restart our scene so we can play again. As we might recall, everything in Unity runs in a scene, SceneManager is what we use to help us transition from one scene to the next. Note: using LoadLevel is depreciated for SceneManager

Now with all of this, we’re almost done!

If we were to try and play the game now and let the knight beat us, you’ll realize a problem. We can’t click on the Restart button!

Let’s fix it.

Allow Clicking on the Button UI

The main reason why we can’t touch our button UI is because of our Group Canvas component attached to HUD. We disabled everything so that our UI will just be something the user sees.

 
0*0sBQ8tNLSRLJBNEP.png

We could enable Interactable and Block Raycasts so that our Graphics Raycaster script will be able to detect the button being clicked, like explained here.

However, if we were to do that, the problem is that everything else in the game would become interactable, including our health bar!

We don’t want that, so instead we’re going to make a separate Canvas Groupcomponent just for GameOver.

We need to do 2 things:

  1. Add a new Group Canvas component and check all settings so that we can interact with our game over panel and ignore the rules set by the parents.
  2. Add a Graphic Raycaster, which is used to detect if the user clicks on anything in the canvas.

Once we have these setup, play the game again and you’ll see that we can restart the game!

 
0*4PyQx-NcAjyQglw5.png

Conclusion

We did a lot of work today!

We:

  • Created a new animation state for our GameOver animations
  • Enabled our animation when our player is defeated
  • Allowed the user to restart the game when they lose

There are some more things that we can add to our Game Over scene to make things more complete, however, tomorrow, we’ll jump into a new topic, specifically enemy spawning!

Until then!

Source: Day 22

Visit the 100 Days of Unity VR Development main page.

Visit our Homepage



0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By JustACicada
      Random Number God has been updated to v1.1.0.
      This is an incremental (although not idle) game about defeating randomized robots by rolling dice and playing cards that alter those dice and their effects.
      Other than performance fixes, the game has been rebalanced from the ground up. Now it should progress in a more fluid fashion. An option to reset the game with a significant boost to your power has been added, allowing you to advance further than you could before.
      There is also now an option to significantly speed up battle animations. Once you learn the rules of the game, a battle can easily take <2 min.
      Windows, Linux: https://justacicada.itch.io/random-number-god
      Android: https://play.google.com/store/apps/details?id=samuelVazquez.randomNumberGod


    • By Jamesgz
      Hey my dudes,
      Me and 4 friends are third year compsci students. Three of us are pretty good at drawing. We are hoping to make a 2d roguelite game with unity during the next few months. We are still brainstorming. At the moment, my idea is to create a card roguelite game:
      First, you would need to choose 2 heroes to enter the dungeon with the goal of finding a treasure. The treasure found gives you extra bonus in later runs. You can choose between mage, gunner, rogue, paladin, warrior and fighter. Each hero has their own unique cards. And there are common cards that every heroes can get(like hearthstone).
      The progression system would be like slay the spire’s. You can choose your own path, but every paths leads to the boss. It would use procedural generation. After defeating an enemy, you get to choose a new card out of the three options. There would be shops, random events, elite enemies, etc
      The combat system is where i need some suggestions on. There would be two piles of deck. One for each hero. I can think of two good combat systems:
      1. Before every enemy encounters, you can choose what cards to use from your deck. Cards not used would not get discarded. Cards are drawn from the deck only if they break or due to special card’s effect. Every card have a durability number. Ones the durability reach zero, the card would break and can no longer be used. Events/enemies can modify the durability of the cards.
      2. Card not used this turn would get discarded. Once the deck is empty, the discard pile gets shuffled and copied to the deck. Card/item effects can increase the number of cards you draw.
      How can I make the game more interesting? Any suggestions would be appreciated.
    • By horror_man
      Hello, I'm currently searching for a talented and passionate programmer to create a small but great horror game that would take around 3 months to be done.
       
      About the game: The game would be a sci-fi/post-apocalyptic survival horror 3D game with FPS (First person shooter) mechanics and an original setting and story based in a book (which I'm writing) scene, where a group of prisoners are left behind in an abandoned underground facility. It would play similar to Dead Space combined with Penumbra and SCP: Secret Laboratory, with the option of playing solo or multiplayer.
       
      Engine that'd be used to create the game: Unity
       
      About me: I'm a music composer with 4 years of experience and I'm fairly new in this game development world, and I'm currently leading the team that'd be creating this beautiful and horrifying game. I decided that making the book which I'm writing into a game would be really cool, and I got more motivated about doing so some time ago when I got a bunch of expensive Unity assets for a very low price. However, I researched about how to do things right in game development so I reduced the scope of it as much as I could so that's why this game is really based in a scene of the book and not the entire thing (and also that's why it would take 3 months). Also I'm currently learning how to use Unity and how to model things with Blender.
       
      Our team right now consists of: Me (Game Designer, Creator, Music Composer, Writer), 3 3D Modelers, 1 Sound Effect Designer, 1 Concept Artist and 1 Programmer.
       
      Who am I looking for:
      - A programmer that's experienced in C# and with Unity.
       
      Right now the game is very early in its development (GDD is completed and all 3D Items, Music and Sound Effects are completed).
       
      If you are interested in joining, contributing or have questions about the project then let's talk. You can message me in Discord: world_creator#9524
    • By kcirkl
      Hello, 
      So, I'm aware this may be a broad question with a vast variety in the anwser. However, I am a game design student that works professionally for a large engineering company conducting software configuration. Naturally, I'm curious about the path ahead and I'm desperately gathering information on the overall process of developement with Unity. Are there professional resources available that can outline the processes and functions of the engine, and what can be used to interact with it? I'm looking for options other than the official documentation. I have already jumped into that. Thanks!
    • By tspartant
      Hey everyone! My name is Ryan and I am the founder of Visualistic Studios, LLC. 
      I'm looking for experienced developers interested in short term and long term contracting. For the past 3 years I've been working in game development contracting, and the past year I've been working full time from home. Since then, I've received more and more contracts and I'm now at the point that I have too many for myself to handle. I have at least another full time job's worth of programming offers, and around 30-80 hours a month for 3D modeling/animation. I also am in need of a UI artist, so if you're talented please contact me! I have contracts using Unity as well as Unreal Engine 4, so if you can program in either please contact me. 
      If you are interested in working on these contracts, please send me links to your work and you hourly rate. (Most contracts range be between 18-25$/h, but please provide your normal hourly rate)
      You can get ahold of me through email - "ryan.hobbs@visualisticstudios.com", or Discord "TSpartanT#4670"
       
      Thank you everyone for reading, hope to hear from you soon!
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!