In most of the games that you will create, you will, more than likely, include the concept of time. This may mean a timer indicating how much time remains before the player loses, or simply, the ability to pause the game.
Implementing a Timer
So first, let’s look at the following snippet example that implements a timer:
float time;
void Update()
{
time += Time.deltaTime;
float seconds, minutes, hours;
seconds = time % 60;
minutes = time / 60;
hours = time / 3600;
print ((int)hours + “:” + (int)minutes + “:” + (int)seconds);
}
In the previous code:
- We use the Update
- We calculate the time since the game started and save it in the variable called time.
- We then calculate the current seconds, minutes, and hours based on the variable time.
If you were to create a countdown, the principle would remain the same, except that the variable time would be initialized to a value that is greater than zero and then decreased every seconds until it reaches zero.
Pausing the Game
In Unity, it is very simple to pause or resume your game, using the following code:
Time.timeScale = 0;//time is paused
Time.timeScale = 1;//time is back to normal
So, you could for example, create two buttons and functions: one button (and its associated function) for pausing the game as well as one button (and its associated function) for resuming the game. You could then call one of these functions based on the button that the player has pressed.