Function Update and yield WaitForSeconds ?

Hi everybody !

I have a really simple question.
I wrote this simple shooting script. My goal for now is to have a delay between the fire.

I know that I can´t use yield WaitForSeconds but I´m sure that there is a really simple solution for that?

Thanks for all answeres !!

#pragma strict

var distancex : float;
var emty_game_object_fire_point : Transform;
var firepoint : Vector3;
var firedirection : Vector3;
var impactpoint : Vector3;
var the_thing_add : Transform;
var the_thing_add_rotation = Quaternion.Euler(0, 0, 0);
var allowfire = true;

function Update(){
firedirection = emty_game_object_fire_point.TransformDirection (Vector3.forward);
firepoint = emty_game_object_fire_point.position;
if (allowfire) {
if (Input.GetMouseButton(0)) {
var hit : RaycastHit;
if (Physics.Raycast (firepoint,firedirection,hit, distancex)) {
impactpoint = hit.point;
Instantiate (the_thing_add, impactpoint , the_thing_add_rotation);
allowfire = false;
//and now wait for seconds and turn allowfire true again 
//to allow shooting again !!?? 

}
}
}
}

A Number of ways to solve this one. The simplest being the forum search or looking in the Documentation :slight_smile:

You could put your instantiate in to a separate function and call it using an invokerepeating which can be canceled with a cancelinvoke

Another way is to capture the Time.time when firing and then comparing this on subsequent updates to get the difference… This code from the documentation does what you need…

// Instantiates a projectile off every 0.5 seconds,
// if the Fire1 button (default is ctrl) is pressed.

var projectile : GameObject;
var fireRate = 0.5;
private var nextFire = 0.0;

function Update () {
  if (Input.GetButton ("Fire1")  Time.time > nextFire) {
    nextFire = Time.time + fireRate;
    var clone = Instantiate (projectile, transform.position, transform.rotation);
  }
}

Sorry, the next time I will look in the Documentation or use the search !

The code is exactly what I needed !

Thanks :slight_smile:

Just an additional bit of info:

I personal HATE coding stupid timestamp based timers in Update(), i think they’re ridiculous and clumsy. It is REALLY easy to code a simple a coroutine that functions exactly the same as Update(), except lets you use WaitForSeconds() yields. Just create a function and use while(true) and a yield, and initialize it in start, like this:

function Start(){
    MyUpdate();
}

function MyUpdate(){
    while(true){
        //do stuff you would do in Update here
        yield;
    }
}

So in your case, you could easily do something like this:

public var shotDelay : float = 0.25;

function Start(){
	ShootUpdate();
}

function ShootUpdate(){
	while(true){
		if(Input.GetButton("Fire1")){
			//do shot stuff
			yield WaitForSeconds(shotDelay);
		}	
		yield;
	}
}

@ legend411

hey that is also a very cool way doing it !!

I will try it :slight_smile: