How to make an Animated Charge Bar
Objective: Create a bar that’ll charge up using IPointerHandler events!
There are some event system’s that we can use from Unity with the UI system. Here are some of the supported events.
To start this project, we will need a background image, a TextMeshPro Text object, a slider, and a button.
They can be placed where ever fits the design.
Now for the coding. We will only need one script. This script will need to grab the UnityEngine.UI, UnityEngine.EventSystems, and TMPro library's.
Once the UnityEngine.EventSystems is grabbed, add in after MonoBehaviour to inherit the IPointerDownHandler and the IPointerUpHandler. When these get typed in, the IDE that is being used will give you an error.
This means that the current script does not implement a certain method from that interface. To do a quick fix, left click the interfaces and on the keyboard hit ALT+Enter and enter again to Implement the interface.
Next is to get a reference to the Slider and the Text, and a float and bool variables.
We will start with OnPointerDown Method that was created. In here we can is _isCharging to true and set the text to say is charging.
In OnPointerUp, set isCharging to false.
To make use of the bool, In Update, check to is if isCharging is true. If it is then check to see if the _charge float is less than or equal to 100. If it is, increment _charge by 50 * Time.deltaTime. Out side of the isCharging if statement, set the sliders value to equal the _charge variable.
This will increase the slider now.
To decrease the bar, check to see if isCharging is false. If it is then check to see if it is greater than or equal to 0. If so, decrement _charge by 300 * Time.deltaTime.
In Unity, drop this script onto the button script.
With this we have a bar that will charge up and cool off quickly just by using the UnityEngine.EventSystem and the Supported Events.
Thank you for reading! Have a wonderful day!