GetMouseButton registering random clicks rather than constant clicks

Greetings everyone,

I am currently creating an FPS game, and I am stuck with this issue.
Basically when I hold the left click button, a variable called “currentAmmo” is being decremented fast rather than constantly. The audio is being “spammed” as well.

What is happening when I press left click: (30, 23, 18, 5… etc). Numbers are random, as this is just an example.
What it should be: (30, 29, 28…)

Below, kindly find the code.

public void shoot()
    {
        //left click
        if (Input.GetMouseButton(0))
        {
            if (aimsight)
            {
                animator.Play("ak47shootSight");
                audioSource.PlayOneShot(ak47Shoot);

            }
            currentAmmo--;
            Debug.Log(currentAmmo);
            if (!aimsight)
            {
                animator.Play("ak47Shooting");
                audioSource.PlayOneShot(ak47Shoot);
            }
        }
    }

Thanks a lot for your help and I apologize for my newbie question.

If this code is being called every frame then yes - that is going to mean bullets are going be firing like crazy!
Your best bet is to use a timer to reduce the firing rate. Not only will this provide a more constant rate of fire, but it will give you flexibility to have different firing rates for different weapons (eg a sub machine may fire faster).

private float timer;
private float fireRate = 0.2f;

public void shoot()
    {
        timer += time.DeltaTime;

        //left click
        if (Input.GetMouseButton(0) && timer > fireRate)
        {
            timer = 0; // Reset timer
            if (aimsight)
            {
                animator.Play("ak47shootSight");
                audioSource.PlayOneShot(ak47Shoot);
            }
            else
            {
                animator.Play("ak47Shooting");
                audioSource.PlayOneShot(ak47Shoot);
            }

            currentAmmo--;
            Debug.Log(currentAmmo);
        }
    }

Tweak the fireRate to how you want it. This should provide a more constant rate of fire.

1 Like

The only thing I would add to matthewseaward’s solution is to make sure that there is just one instance of shoot() happening in the scene i.e there is only one gameobject placed in the scene with shoot() called in it’s update.

1 Like

Thanks alot this worked!!! I really appreciate your help guys, will do as suggested!