top of page

Coroutines-006-Timers

Project Files for the course - Download

1.1 Introduction

1. In this tutorial we are going to learn how to use coroutines in Unity to build timers.

2. We are going to build two types of timers that is an Int Timer and a Float timer.

3. Open the Scene006 to get started with the project.

1.2 Scene Descriptiong

1. In the scene we have made a textMeshPro object that is going to display the timer.

2. In addition to this we have created a script called CoroutineTimer attached to Coroutine Timer gameObject that is responsible for running a timer.

image.png

3. Let us now edit the script and let us start writing some code.

1.3 Making a Timer

1. To the script let us add three methods that is StartTimer(), StopTimer() and ResetTimer() which will be responsible for StartingStopping and Resetting the timer. Also add attributes on the top so that the methods could be called from the editor.

image.png
image.png

2. Now let us write a coroutine called TimerCoroutine().

3. In this coroutine we are going to increment the elapsedTime by Time.deltaTime after a delay of yield return null(that is Time.deltaTime)

4. This will be added every single frame as it is running in the while loop.

image.png

5. Let us now complete the remaining timer methods of Start, Stop and Reset Timer.

6. To have the ability to stop the coroutine we need a Coroutine variable that will hold a reference to the running coroutine.

image.png

7. Let us now complete the start and stop methods which are fairly simple.

8. For starting let us assign the timerCoroutine to the started coroutine.

9. To stop the coroutine let us use the StopCoroutine method keeping in mind if the coroutine is running or not.

image.png

10. Let us complete the ResetMethod() whose only job is to 0.

image.png

11. Let us now define two Timer modes that is Int Mode and Float Mode.

12. Depending on the timer mode the time text would be different like 3 or 3.12 seconds.

image.png

1.4 Setting the text.

1. Let us now set the text for the timer

2. Whenever the elapsed Time value is changed or the clock is Reset the timer value will be changed.

3. Let us write SetTimerText() method.

4. This will set the timer based on whether the time is int mode or the float mode.

5. We will set the timer value to TextMeshPro.

image.png

6. Let us now add the SetTimerText() to the coroutine and ResetTimer() method.

image.png

6. Let us now add the SetTimerText() to the coroutine and ResetTimer() method.

7. As you can see from the example above the Start(),Stop() and Reset() methods are all working and we are able to toggle the mode to Int Mode and Float Mode.

bottom of page