Ammunition goes down at more than one at a time

I have been making an fps and I am adding ammunition but I am testing it and the ammo goes down at more than one at a time so it goes from 10 to 6 when you click once to fire.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour {
    public int maxammo = 10;
    private int currentammo;
    public float reloadtime = 1f;
    public float damage = 100f;
    public float range = 10000000f;
    public Camera fpscam;
    // Use this for initialization
    void Start () {
        currentammo = maxammo;
    }

    // Update is called once per frame
  

    private void Update()
    {
       if (currentammo <= 0)
        {
            Reload();
            return;
        }
        if (Input.GetButton("Fire1"))
        {
                    Fire();
        }
    }
  
    void Reload() {
        Debug.Log("reloading");
        currentammo = maxammo;
    }

void Fire()
    {
        currentammo--;
        RaycastHit Hit;
       
        if (Physics.Raycast(fpscam.transform.position,fpscam.transform.forward, out Hit, range))
        {
            Debug.Log("hit");
            Target target = Hit.transform.GetComponent<Target>();
            if (target != null)
            {
                target.TakeDamage(damage);
            }
        }
    }
}

I feel like that’s because you have no conditions regarding when the weapon can be fired. Whenever you press the Fire1 button, the weapon will shoot ammo. As a human it’s really hard to only press the Fire1 button for 1 frame. You are currently holding the Fire1 button for multiple frames, seeing how your input logic is within the Update loop. This causes your ammo to deplete very fast as well.

You could consider using GetButtonDown, or add a timer that allows the weapon only to shoot ever X seconds.

void Update()
{
    // update the timer to increase whenever it's still below a certain delay (let's say 0.5 seconds)
    if (shootTimer < shootDelay)
    {
        shootTimer += Time.deltaTime;
    }
 
    if (Input.GetButton("Fire1"))
    {
        Fire();
    }
}

void Fire()
{
    // exit this function if the timer is still below the delay, so for example "if 0.3 < 0.5"
    if (shootTimer < shootDelay)
    {
        return;
    }
 
    // if shootTimer is bigger than shootDelay, that means 0.5 seconds have passed, and the weapon may fire
    currentAmmo--;
    
    // reset the timer back as well
    shootTimer -= shootDelay;
}

EDIT: Forgot to reset the timer. :stuck_out_tongue:

1 Like

Thanks for the help!