How to make an Animated Charge Bar
--
Objective: How to make an Animated Charge Bar.
Before doing anything I set my canvas like this nothing fancy, If you are new to my article go to see how to work with the slider, buttons, etc.
In the first step, create a new script called ChargeBarButton, then create these variables.
Now since we need to perform an action then do something to the UI component whether a button or UI-related module.
The Best practice to do an action and then perform some task using UI is to use Unity Event.
Here is a link to the Unity Event documentation. https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/SupportedEvents.html
In this step I want to use my button to charge the charging bar, I will do this using IPointerDownHandler.
But Suleiman how could I implement this IPointerDownHandler, It scares me.
First Understand this, the events supported by the Standalone Input Module and Touch Input Module are provided by interface and can be implemented on a MonoBehaviour by implementing the interface.
StandAlone Module is like Button, Slider, etc.
So let's Implement this interface to our ChagingBarButton, then we will implement this interface. Implementing this interface means this interface will force us to implement its base method to work. The name space of this is Namespace: UnityEngine.EventSystems
Go to the Update method and check if _isCharging is equal to true, here we need to add _chargeAmount by some value and then multiply it by Time.deltaTime, to make sure it charges by every second. Then we update slider value with _chargingAmount and we update our text.
But this will charge even if we pass the maximum slider value, so we need to charge the bar if the charging amount is less than the slider's maximum value.
But how we could know if it's time to charge our bar is when we press the button, so let's set _isCharging to true on OnPointerDown and set to false OnPointerUp which I will implement it now.
Now go to the update and reverse the charging logic, Here I will set the higher value to discharge quickly.
Select the button Attach the script and fill in the required variables.
Now I will create blink behavior for the button but only when the button is pressed, I have covered this so I will go super quick. I will do this for the Fill area of the slider too.
I will add other logic to make the Fill area blink quickly if the charge amount is a different amount. We do this using the speed variable of the animator, so create the animator variable and drag and drop fill there, then check the Charge amount and set the speed from 1 to more, the bit number the quick animation will play.
Call this method when we are charging, we do this when is charging is true.
This is how I create an Animated Charge Bar.
See you in the next one.