Limit ammo
I am trying to make a single script in my game that covers all the combat system, and it is working as expected, but i am having a problem with the ammo part on it. I have a text and a public int named Ammo. The int holds the ammount of bullets that i have. Everytime i shoot, i will have one less bullet and so it goes. The problem is, when Ammo reaches 0 i can still shoot, and it goes indefinetely with negative numbers, such as -1,-2,-3... How would i limit my ammo so when i have 0 bullets the number will NOT change anymore, or just stay at 0?
I was trying to limit Ammo by using this, but it doesn't work:
if (ammo == 0) //If ammo is equal to zero, Then | I also tried (ammo == curammo) curammo being a int with value 0.
{
ammo = 0; //Then, ammo is equal to zero and it stays there. | As i said before, using curammo, it would be like ammo = curammo then it would always stay at 0.
UpdateAmmo(); //This updates my UpdateAmmo function.
}
This is my UpdateAmmo function, it make my text be equivalent to the ammo int so i can know how many bullets i have.
void UpdateAmmo()
{
txt.GetComponent<UnityEngine.UI.Text>().text = ammo.ToString();
}
Answer by dacarrera · Nov 27, 2016 at 09:04 AM
I'm not sure what the rest of your code is, so you'll just have to amend this as needed.
Essentially you can just add an if()
statement (as you were doing) but you should first check if ammo > 0
then run your function.
if(ammo > 0){
// Run whatever functions you want
// when you have ammo
}
else{
// everything else
// AKA you don't have ammo (ammo <= 0)
// also make sure ammo.text is set to 0
}
Answer by ma22be61 · Nov 27, 2016 at 10:31 AM
First off , are you sure your ammo quantity is actually connected to the number of bullets or the shooting function? Maybe it's only "connected" to the textui and not the gun?
void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse1) && ammo >=1)
{
ammo = ammo -1;
UpdateAmmo();
}
else if (Input.GetKeyDown(KeyCode.Mouse1) && ammo ==0)
{
//STOP SPAWNING BULLETS
}
}