Time for action – adding code to pause the game Scene

In BeginState, we're going to set timeScale to zero to pause the Scene. Then before switching to PlayState, we'll set it back to normal speed. Perform the following steps:

  1. Modify BeginState in two places as shown in the next screenshot.
  2. Save the file.
    Time for action – adding code to pause the game Scene

What just happened?

An analysis of the code shown in the preceding screenshot is as follows: On the BeginState class

Line 14: Time.timeScale = 0;

  • This line makes time in the game to stop

Line 29: Time.timeScale = 1;

  • This sets the game speed back to normal when switching to PlayState

Click on Play again. Now the Cube GameObject is suspended in air. Click on the Press to Play button and everything is back to normal and you're in PlayState.

Notice how the button disappears when you change States. Once again, this shows the beauty of the State Machine. You don't have to use a bunch of if statements to make things appear or disappear. Each State determines the control you want and what shows on the screen.

Changing the State using a timer

It's great being able to stop time like that, but what if you wanted BeginState to be active for only a few seconds and then automatically change to PlayState? By setting timeScale to zero, any timers are now frozen in time.

Unity has a timer that runs, no matter what. It's a variable in the Time class called realtimeSinceStartup. When Play is clicked, this variable is constantly updated with the running time of the game. We can use this to create a simple timer in BeginState to make it switch to PlayState.

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

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