Per usual, I spent too much time on one feature, and while I don’t have much to show for it, I feel as though understanding the feature and being able to explain it will help me down the road. On days like these, I like to think I’m investing.
With what limited time I had today I focused on my revamping my Ammo display. For now I’ve decided on an Ammo maximum of 150. This amount will essentially be shown by 15 laser icons, each of which will gradually disappear as the Ammo amount grows lower.
The way I’ve done this is essentially by creating an Array of 15 Laser GameObjects with Image components, but 15 GameObject references can get tedious to assign in Unity Inspector, plus what if I want to change them? So I’ve assigned the Array references in script, and even adjusted the Array length to match the amount of Laser GameObjects there are. I’ll maybe try and explain that in my next article. I’ve set each GameObject Image Component as type Filled, which assigns it a variable through which I can make it look as though it’s disappearing.
So I have anywhere from 0 to 150 Ammo, which I want visualized in game. A great way to communicate that amount is essentially through a percentage. If I have 90/150 Ammo, I divide those two numbers and get 0.6, or 60%. So I want my Laser Image Components to reflect 60% capacity. 15 Laser visuals representing 150 Ammo, so each Ammo spent is 10% of a Laser. 125 Ammo is 75% capacity, or 12.5 Lasers. There’s a ton we can do with that information now.
The numbers are set up in a way that’s both convenient and demonstrative. I have 150 potential Ammo, 15 Ammo Objects with Image Components, and a variable adjusting each Image, ranging between 0 and 1. I can use current Ammo to communicate three things to me through two additional formulas:
- int ammoInt = (ammo / 10);
- float ammoFloat = (ammo - (ammoInt * 10f)) / 10f);
And now with each potential amount of Ammo, I can reference all the needed variables with pertinent information.
- At 147 Ammo, I want 14 visuals at 100% or 1.0f, and the 15th at 0.7f
- At 125 Ammo, I want 12 at 1.0f, the 13th at 0.5f, the rest at 0
- At 67 Ammo, I want 6 at 1.0f, the 7th at 0.7f, and the rest at 0
- At 13 Ammo, I want 1 at 1.0f, the 2nd at 0.3f, and the rest at 0
Seeing the pattern? I get an integer from the Tens and Hundreds digits in Ammo to tell me what GameObject I should be adjusting the fill for. And I take the Ones digit and turn it into a float value to assign that fill amount.
In this edition of One Letter Ruined My Life!!, see how I spent 20 minutes confused over why a simple math formula didn’t work.
I cannot stress using Debug.Log enough. Use it to test every little part of your methods, it’ll verify that each step of the process is working and it’ll tell you the value for every variable you want measured along the way.