To create an animated progress bar, follow these steps:
- Import the progress bar image to Unity and set its type to Sprite (2d and UI).
- Open a scene and create a new Image by using the Game Object | UI |Image command.Canvas and Image game objects will be created.
- Select the Image game object and change its name to ProgressBar.
- Find the Image component in the ProgressBar game object's Inspector.
- Set the Image Type property to Filled, the Fill Method to Horizontal, and the Fill Amount to 0, as shown in the following screenshot:
- By changing the Fill Amount, value you can animate a progress bar. You can do it with an Animation View, but it makes more sense to use a script here.
- Create a new script and call it ProgressBars.cs (you can also use the same script provided with the example Unity project; you can find it in the Scripts directory of this recipe). Make sure to include the UnityEngine.UI namespace in the script. Write the following line in the Update() function:
image.fillAmount += Time.deltaTime * fillSpeed;
- The image object is a reference to the Image component on the same game object. We assign it in the Start() function by calling the line:
image = GetComponent<Image>();
- The fillSpeed variable is a public float variable that describes the fill amount increment per second.
- In this simple script, we increase the Fill Amount of the Image component in time.
- Assign the script to the ProgressBar game object and play the game to see the effect.