Reputation: 41
Im trying to program a system in an FPS unity game where every time you deplete 12 bullets the program takes another 12 from a stock pile. The issue is, if the stock pile is greater than 12, and you deplete the 12 bullets already loaded into your gun, the entire stockpile disappears. Ive scanned my code and am completely perplexed as to how to fix this error. The main code for this operation is below.
if (bulletsLeft <= 1)
{
if (extraBullets > 0)
{
if (extraBullets <= 12)
bulletsLeft += extraBullets;
extraBullets -= extraBullets;
}
if (extraBullets >= 12)
{
bulletsLeft += 12;
extraBullets -= 12;
}
}
Upvotes: 0
Views: 86
Reputation: 112324
Since you forgot the braces, your code ...
if (extraBullets <= 12)
bulletsLeft += extraBullets;
extraBullets -= extraBullets;
... is equivalent to
if (extraBullets <= 12) {
bulletsLeft += extraBullets;
}
extraBullets -= extraBullets; // No more bullets after this!
The next statement ...
if (extraBullets >= 12)
... will never be performed.
I suggest to simplify the logic and to first determine how many bullets to transfer from the stock pile. Then perform the transfer.
if (bulletsLeft <= 1) {
int transferBullets = extraBullets < 12 ? extraBullets : 12;
bulletsLeft += transferBullets;
extraBullets -= transferBullets;
}
The assignment with the ternary expression...
int transferBullets = extraBullets < 12 ? extraBullets : 12;
... is equivalent to
int transferBullets;
if (extraBullets < 12) {
transferBullets = extraBullets;
} else {
transferBullets = 12;
}
According to @Kyle and @UnholySheep, you can also write this instead:
int transferBullets = Math.Min(12, extraBullets);
Upvotes: 2