Day 93 — Making a Game Out of a Progress Bar
A progress bar or fill bar is a common UI component found in all kinds of applications. In games, it’s often used to indicate player health or mana supplies, or maybe how much fuel your car has. I’m going to demonstrate how to implement a progress bar and at the same time show how to control it with the Unity input system. While we’re at it, why not make a game?
To start things off, I added a slider control to my UI. (Figure 1)
My next task is turning this standard slider control into a progress bar. The slider control is made up of three different components. The Background, Fill Area, and Handle Slide Area. (Figure 2)
To convert this into a progress bar, I simply deleted the handle. I then turned the fill color to red, rotated it to be vertical, and made it bigger since it’s the main feature in the game. (Figure 3)
With the progress bar in place, it’s time to start thinking about input. My idea was to have the player press the space bar and hold it to fill the progress bar as long as they can without filling it all the way. To do this, I installed the new Unity Input System from the package manager. (Figure 4)
I then added an Input Actions asset to the project and called it “UIInputActions”. To that, I added an Action Map called “ProgressBar” with a single Action called “Fill”. The Fill Action is bound to the keyboard spacebar. (Figure 5)
To round out the UI, I added a current fill level and high score text, along with some instructions for the player. (Figure 6)
For the code, I created a new C# script and attached it to the slider object. I created an instance of the Input Actions object created earlier and a reference to the slider control. (Figure 7)
Next, I registered for the started and canceled events from pressing the keyboard space key that I added to the Action Map earlier. The started event will fire when the player first presses the key. The canceled event will fire when they release the key. (Figure 8)
The logic for the progress bar works by setting a Boolean to true when the button is first pressed and then started a Coroutine. In the Coroutine, as long as the Boolean is true, the progress bar will fill at a rate of half a second from 0 to 1. When it reaches 1, the progress bar is full and then will take a full second to go back down. (Figure 9)
For the game logic, I keep a running high score for any value less than 1. I display that as well as the current fill value as the button is pressed. (Figure 10)
To give the game a bit of polish, I slowed down the rate of the de-fill and turned the fill color red if the player hits the max fill value, otherwise it’s green. (Figure 11)