Unity UI: Changing The Width Of A RectTransform

So I wanted to add some more functional detail to my Ammo Bar UI, and decided to make the laser beams get smaller as you use ammo.

In my UI Manager script:

Create an array of RectTransforms (since I have 2 I need to modify)
RectTransforms are the Transform equivelant component that is on every Unity UI object
I add a For loop to my existing UIManager ChangeAmmo function

Since I want the width to be between a custom range (23.48 - 64), I needed to convert the ammo range (0 - 15) into the custom range.

NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin;

Now the width runs smoothly between 23.48 and 64, in parallel to the ammo as it runs between 0 and 15.

Looking at the Ammo UI, you can see the laser width decreasing nicely as the ammo is used:

Width decreases as ammo is consumed, and increases as it is restored

--

--

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.