# How to limit the players rate of fire?

Hey,

I’m working on a space shooter and right now the player can shoot as fast as you can push the space bar and I just wanted to know how I would go about changing my script to limit the players rate of fire. All I have right now is just a basic piece of code that fires a bullet prefab, and the bullet prefab moves up the screen and checks for collisions with enemies then adds score.

this is what I have right now for the player shooting:

If (Input.GetKeyDown(“space”)){

``````var tempBullet: Rigidbody;

tempBullet = Instantiate(bullet, transform.position, transform.rotation);
``````

}

How would I limit this?

Any help is appreciated

Thanks.

try this

private var allowfire : boolean = true;
var tempBullet: Rigidbody;

``````function Update()
{
if((Input.GetButtonDown)&&(allowfire))
{
Fire();

}

}

function Fire()
{
allowfire = false;
tempBullet = Instantiate(bullet, transform.position, transform.rotation);
yield WaitForSeconds(rate with which you want player to fire);
allowfire = true;
}
``````

it have fire rate and prass space

``````var tempBullet : Rigidbody;
var fireRate = 0.5;
private var lastShot = 0.0;

function Update()
{
If(Input.GetKeyDown("space"))
{
Fire();
}
}

function Fire()
{
if (Time.time > fireRate + lastShot)
{
tempBullet = Instantiate(bullet, transform.position, transform.rotation);
lastShot = Time.time;
}
}
``````

Try This
{
public float speed;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;

``````void Update ()
{
if(Input.GetButton("Fire1")|| Input.GetKeyDown(KeyCode.Space)&& Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
GetComponent<AudioSource>().Play();

}
}
``````

}

using UnityEngine;
using System.Collections;

``````public class ShootBullets: MonoBehaviour {

public GameObject spawnPoint;
public Rigidbody projectilePrefab;
public float speed;
public float fireRate = 1.0f;
private float lastShot = 0.0f;

void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
if (Time.time > fireRate + lastShot) {
Rigidbody hitPlayer;
hitPlayer = Instantiate (projectilePrefab, transform.position, transform.rotation) as Rigidbody;
hitPlayer.velocity = transform.TransformDirection (Vector3.forward * speed);
lastShot = Time.time;
}
}
}
}
``````

This code works perfectly for me. It allows for the speed of the projectile to be changed as well as the fire rate. The only thing I noticed was that the player cannot shoot immediately once the game is started. Minor setback, however, I am interested in figuring out a way to allow the player to shoot once the game starts, and THEN be limited.