- Home /
yield WaitForSeconds
I am trying to get the gun to wait for a second before it fires however it just fires an instant stream, why doesn't it wait ?
#pragma strict
var Target:Transform;
var damp = 1.0;
var bulletPrefab: Transform;
function Update () {
if(Target)
{
var rotate = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
}
Shoot();
}
function Shoot()
{
yield WaitForSeconds(1);
var bullet = Instantiate(bulletPrefab, GameObject.Find("EbulletSpawnPoint").transform.position, Quaternion.identity);
bullet.rigidbody.AddForce(transform.forward * 1000);
}
You're calling Shoot
every frame (inside the Update function).
Answer by Eric5h5 · Jul 09, 2012 at 06:06 PM
You're starting a new instance of Shoot every frame in Update. You need to yield on a coroutine if you want it to wait, but you can't yield in Update. What you should do is not use Update for shooting at all, but rather InvokeRepeating.
#pragma strict
var Target:Transform;
var damp = 1.0;
var bulletPrefab: Transform;
function Start () {
InvokeRepeating ("Shoot", 1.0, 1.0);
}
function Update () {
if(Target)
{
var rotate = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
}
}
function Shoot()
{
var bullet = Instantiate(bulletPrefab, GameObject.Find("EbulletSpawnPoint").transform.position, Quaternion.identity);
bullet.rigidbody.AddForce(transform.forward * 1000);
}
Answer by FLASHDENMARK · Jul 09, 2012 at 01:54 PM
#pragma strict
var Target:Transform;
var damp = 1.0;
var bulletPrefab: Transform;
var rateOfFire = 1.0;
private var lastShot = -10.0;
function Update () {
if(Target)
{
var rotate = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
}
Shoot();
}
function Shoot()
{
if(Time.time > rateOfFire + lastShot){
var bullet = Instantiate(bulletPrefab, GameObject.Find("EbulletSpawnPoint").transform.position, Quaternion.identity);
bullet.rigidbody.AddForce(transform.forward * 1000);
lastShot = Time.time;
}
}
I usually find it bad practice to use WaitForSeconds. I prefer using a simple "timer", but that is just me.
It should now shoot every second.
Answer by Afonso-Lage · Jul 09, 2012 at 07:03 PM
You can also use a variable to check if it is shooting:
if (!isShooting){
yield WaitForSeconds(1);
var bullet = Instantiate(bulletPrefab, GameObject.Find("EbulletSpawnPoint").transform.position, Quaternion.identity);
bullet.rigidbody.AddForce(transform.forward * 1000); isShooting = false; }
And before you call Shoot(), you set isFiring to true;
Your answer
![](https://koobas.hobune.stream/wayback/20220613073920im_/https://answers.unity.com/themes/thub/images/avi.jpg)