Troubles with shooting cooldown (Top-down)

I have a trouble, that sometimes my “gun” object fires twice, with about 0.1 second cooldown.
I dont know how to fix that problem, I implemented 2 types of bullet cooldown using Time.time and making variable that lose 1/50f every FixedUpdate frame, but no one of this systems doesn’t work properly. Help me please.

“Player_shoot code”:

    public GameObject bullet;
    public GameObject enemy;
    public float bulletCd = 1f;
    public int damage = 1;

    private float shootTimer = 0;

    void Update()
    {
        if (Input.GetMouseButton(0) && shootTimer <= Time.time) {
            shootTimer = Time.time + bulletCd;
            Fire();
        }

        if (Input.GetMouseButtonDown(1)) {
            SpawnEnemy();
        }
    }

    void Fire() {
        bullet.transform.position = transform.position;
        bullet.transform.rotation = transform.rotation;
        bullet.gameObject.SendMessage("SetDamage", damage);

        Instantiate(bullet);
    }

Hey,

On line 11, change Input.GetMouseButton(0) to Input.GetMouseButtonDown(0).

This will make it impossible to shoot more than 1 bullet at a time.

The reason you sometimes fire 2 bullets with a 0.1 second cooldown is likely because you’re holding the mouse button for more than 0.1 seconds.

try something like this

    public GameObject bullet;
    public GameObject enemy;
    public float bulletCd = 1f;
    public int damage = 1;

    private float shootTimer = 0;

public bool OnCooldown = false;

    void Update()
    {
        if (Input.GetMouseButton(0) && OnCooldown ==false) {
            OnCooldown = true;
StartCoroutine(CDTimer);
            Fire();
        }

        if (Input.GetMouseButtonDown(1)) {
            SpawnEnemy();
        }
    }

public IEnumerator CDTimer(){

yield return new WaitForSeconds(bulletCd);
OnCooldown = false;
}

    void Fire() {
        bullet.transform.position = transform.position;
        bullet.transform.rotation = transform.rotation;
        bullet.gameObject.SendMessage("SetDamage", damage);

        Instantiate(bullet);
    }
1 Like

Thatks everyone for help. Especially rarac. But I’m an idiot and I had two scripts, one “Gun” and one more on “Player”. Yeah…