Creating a linear timer

In this recipe, we are going to create a linear timer. In this instance, the timer is shown as a long bar that shortens over time. An example of this would be when we want a player to make a decision within a short period of time, such as during a dialog choice to progress the narrative. In this case, the timer may feature above or even below the choices to indicate the amount of time that the player has left to decide. To achieve this, we will use the Image (Script) component and develop a script to manage the length of the bar according to the time remaining.

How to do it...

  1. First of all, we need to create a bar for our timer. To do this, we can open a graphics program to create it. Alternatively, we can just use the bar that we created in the Implementing a linear heath bar recipe in the previous chapter.
  2. Next, we need to import the bar into our project and set Texture Type to Sprite (2D and UI) so that it can be set as Source Image in our UI components. Then click on Apply. Of course, this is not needed if our project is set to work in 2D mode.
  3. Now, we can create a new UI image inside Unity. To do this, right-click on the Hierarchy panel and then navigate to UI | Image. Next, rename it to Linear Timer.
  4. Inside the Image (Script) component, we have to change Image Type to Filled. As a result, we can decide how much of the image is filled. Furthermore, the component should change a little in the Inspector.
  5. Let's change Fill Method to Horizontal and Fill Origin to Left. Of course, we have to add the bar that we previously created to Source Image. Finally, we can place Linear Timer wherever we want, using Rect Tool or the keyboard shortcut T.
  6. If we want to maintain the original proportion of the bar, we can click on the Set Native Size button in the Inspector.
  7. Then, in Linear Timer, navigate to Add Component | New Script, name it BarTimerScript, and then click on Create and Add.
  8. Double-click on the script to edit it and, as always, add the using UnityEngine.UI; statement at the beginning of the script. This ensures that we are able to manipulate the UI elements within the script.
  9. Before we add any functions, we need three variables: two private and one public. We will set the last one in the Inspector. To do this, we can write the following code:
    private Image barFilling;
    public float timeAmount;
    private float time;
  10. In the Start() function, we have to set up the time variable along with the barFilling one, by adding these lines:
    void Start () {
      barFilling = this.GetComponent<Image> ();
      time = timeAmount;
    }
  11. Finally, in our Update() function, we have to decrease the time variable by the time that has elapsed from the last frame, and update the filling of the bar so that it can reflect the amount of time that has elapsed. Therefore, we can script the following:
    void Update () {
      if (time > 0) {
        time -= Time.deltaTime;
        barFilling.fillAmount = time / timeAmount;
      }
    }
  12. Now, once we have finished the script, we can save our work. If we click on play, we should have something that looks like this:
    How to do it...

How it works...

After we have imported the image, we can set it to Sprite (2D and UI) (this is not needed if the project is in 2D). Next, we can change its Fill Method field to Horizontal and set Fill Origin to Left so that the image can disappear gradually as the time decreases, starting from the right-hand side.

Then, we have created three variables in our script. The first variable, barFilling, stores the reference to the Image (Script) component, which is attached in the same game object of this script. The second variable, timeAmount, is the starting value of time for the countdown, in seconds. Finally, the third variable, which is time, contains the time that is remaining.

In the Start() function, we first assigned the barFilling variable by calling the this.GetComponent<Image>() function. Then, we set the time to timeAmount so that the countdown begins with a specific starting time.

Finally, in the Update() function, we set the ratio between time and timeAmount to the fillAmount variable. This is contained in the Image (Script) component of Linear Timer. In fact, the ratio is the percentage of time left and also how much longer our linear timer should be.

There's more...

The first of the next two sections will explain to us how to improve our timer by running some code after the timer expires. The second one, instead, will give us an idea about how to quickly change the design of our timer.

Running code when the timer expires

In order for something to happen after the time has expired, such as loading the game on the screen, or triggering the sound of a closing door because the player shouldn't be able to reach it after the time limit, we have to add a new variable to our script:

private bool isOver;

Also, add an else branch inside the Update() function after the if statement, in the following way:

else{
  if(!isOver){
    isOver = true;
    //DO SOMETHING
  }
}

We use the isOver variable to trigger the time elapsed event only once after the time expires. In order to test it, we can write something in the debug console by calling this function:

Debug.log("Timer expired!");

Creating a double-sided timer

In some cases, we might want a timer that animates on both ends, adding intensity to the game by providing the player with a heightened sense of urgency. To achieve this, we can use two linear timers that are synchronized; just make one specular to the other.

See also

  • For different kinds of timers or countdowns, refer to the Implementing a numeric timer, Implementing a radial timer, Creating a mixed timer, Creating a well-formatted timer, and Developing a well-formatted countdown that changes recipes, which are all contained in this chapter
..................Content has been hidden....................

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