How do I add a delay to my shooting function?

Hello all.
New Unity scripter here.

I currently have a function that allows my player to shoot bullets while left mouse button is held down. The problem is, the bullets shoot out the gun at an alarming rate, to the point where the map is filled with bullets and the player is pushed back when shooting.

I’ve tried to add a WaitForSeconds(); to the end of the update function, but it just errors out. How can I add a wait function directly after my bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed; line? Thanks in advance! :slight_smile:

Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Gun : MonoBehaviour
{
    //def variables
    public Transform bulletSpawnPoint;
    public GameObject bulletPrefab;
    public float bulletSpeed = 10;
 
    void Update()
    {
        //detect LMB down
        if(Input.GetMouseButton(0))
        {
            //create new bullet from the prefab
            var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
            //create velocity
            bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed;
        }
    }
}

Hi @gregulous, Here is how I do it:
Add a couple new floats shootTimer = 0 and shootDelay = 1
In the update method increase the shootTimer by Time.deltaTime;
Put an if statement around your bullet code to only shoot if the time has reached the delay.

shootTimer  += Time.deltaTime;
if (shootTimer > shootDelay){ 
    shootTimer = 0;
    var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation); //create velocity
    bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed;
}