- Home /
Am I missing something when it comes to basic math?
Okay, I have this really small reloading function, that is called when I press 'R'
int clipAmmo;//Is set to clipSize in Awake ()
int clipSize = 7;
int totalAmmo = 14;
void Reload () {
if (totalAmmo >= clipSize) {
clipAmmo = clipSize;
totalAmmo -= clipSize;
} else {
clipAmmo = totalAmmo;
totalAmmo = 0;
}//else
}//Void Reload
Looks good right? Somehow when ever I press 'R' to reload, clipAmmo and tottalAmmo sets itself to 0. I have zero clue in what's going on because this is just simple math. WHAT AM I DOING WRONG?
Any help is appreciated.
Answer by Arkaid · Jul 14, 2016 at 05:44 AM
The code and the math is fine. So I'm guessing that Reload is getting called repeatedly when you press R, quickly depleting your ammo to 0
Also, this is prettier and easier to read:
void Reload ()
{
// load the clip with whichever is the smallest amount
clipAmmo = Mathf.Min(clipSize, totalAmmo);
// reduce total ammo by amount filled
totalAmmo -= clipAmmo;
}
That said, that code doesn't check if the clip is already full (which is also why you're depleting ammo on reload). This will fix that:
void Reload ()
{
// how many bullets can we fill?
int fill = clipSize - clipAmmo;
// load the clip with whichever is the smallest amount
clipAmmo += Mathf.Min(fill , totalAmmo);
// reduce total ammo by amount filled
totalAmmo -= fill;
}
It was around 11P$$anonymous$$ when I ran into this issue and forgot all about the difference between Get$$anonymous$$eyDown and Get$$anonymous$$ey. So you were rightl.
Note: The second solution provides different mechanics than the original code. It actually "refills" the current clip ins$$anonymous$$d of changing the clip. It of course depends on what functionality you want. In reality if you change a clip which isn't yet empty those bullets are "wasted" / stay in that removed clip. A lot shooters that claim to be "realistic" do it that way.
Of course there are a lot of games that don't really have "clips" but an amout of loaded bullets and some reserve ammo (like Half-Life, Unreal, ...). So firing a single bullet and then reload would simply replace that one bullet in the clip ins$$anonymous$$d of replacing the clip as a whole.
The different mechanics have a huge impact on tactical reloading strategies of the players.
Your answer
![](https://koobas.hobune.stream/wayback/20220612084801im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Implement the equation as a code? 1 Answer
How would you fake air resistance? (c#) 2 Answers