How to shoot once a second?

I need the projectile to be instantiated once every second. Instead the projectiles instantiate like crazy.

function Update(){
if (Vector3.Distance(transform.position, p1.transform.position) < 10)
    InvokeRepeating("Shoot",0, 1);

function Shoot()
	Instantiate(projectile, shooter.position,shooter.rotation);



The reason it “shoots like crazy” is because you keep calling InvokeRepeating, so after a couple frames you have a couple hundred InvokeRepeating calls, each of which start a new “loop” of calling Shoot.

My suggestion is to not use Coroutines (because I don’t like them XD), but instead make a simple timer

//shootTimer is a forward timer, holding the time when the shoot event should next be executed
private var shootTimer:float = 0;
//shoot represents wether we should shoot or not
private var shoot:boolean = false;

function Update() {
    //Decide wether to be able to shoot or not
    if (Vector3.Distance(transform.position, pl.transform.position) < 10) {
        shoot = true;
    else {
        shoot = false;
    //If we should shoot and if we can shoot, then we do so
    if (shoot && shootTimer < Time.time) {
        //After calling Shoot() we need to reset the timer, so that we only shoot once a second
        shootTimer = Time.time + 1;
        //1 can be replaced by anything and prepresents the time when this should next be called

This is just a simple implementation of a timer. I can’t tell if it’s exactly what you want, however I’m sure you can figure out how to change it :slight_smile:

Hope this helps,

My guess is you’re doing this in Update and the distance check is ‘true’ about 60 times per second. You might want to set a boolean like ‘isShooting’ to true if it wasn’t and start the InvokeRepeating then and only then.