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:
BeginState
in two places as shown in the next screenshot.An analysis of the code shown in the preceding screenshot is as follows: On the BeginState
class
Line 14: Time.timeScale = 0;
Line 29: Time.timeScale = 1;
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.
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
.
52.15.74.25