HUD in Unity for Shift key thrust
3 min readJun 3, 2021
The exercise here demonstrates creating a HUD element in the UI canvas and controlling the behavior through code.
- Create an image element (name it “Frame”) in the canvas and attach a frame’s sprite to it.
- Create an empty object (name it “ThrustBar”) and drag the image element above it to make it a child of this object.
- Create another image element (name it “Fill”) and place it within the frame by using the alt + stretch option.
- If interested, bring in a visual element in form of an image that can depict a thruster and make it a child of the empty object above as well as align as needed.
- Add a slider component to the ThrustBar which is going to allow scaling of fill element.
- Drag the fill element to the “rect” option of the slider component.
- For the scale value, choose a number as per preference. (Whole number checkbox shall be clicked if the required change needs to happen in a whole number manner and not a real number.)
- Add a script component to the ThrustBar that can contain a method to alter the scale value.
The HUD is now in good shape. The next requirement is to alter it using code.
- The thruster script should have a method to change the value of this slider scale.
- Drag the slider component to the public variable of this script of type “Slider”.
Now, this method has to be called from the place that handles the left shift key press mechanism.
- In the script that handles it, declare a variable of the type “ThrustBar” to get a reference.
public ThrustSlider _healthBar;
- Create a method to decrement the slider value in the same script using the handle create above. (Do not forget to place a null verifier.)
- Create a coroutine to increment the slider value when the shift key is released. (A method can not work here because this must happen in parallel.)
- The coroutine here should check if the value of the slider is less than 1 to decrease the increment speed a bit until it goes past 1 and then shifts gears. (This will stop the player from thrusting constantly.)
- Finally, use both these in the left shift key method. Also, get a handle on the current value of the slider to compare and alter accordingly.
This should be it :)
Here is the final result.
Thank you very much