WaitForSeconds behaves weirdly

Hello! So im trying to write a script where a bullet is being instantiated every 5 seconds… The problem here is that when the game starts, it waits for 5 seconds, then immediately instantiates bullets every frame and doesnt wait for 5 seconds anymore. What’s wrong with my script?

public class shoot : MonoBehaviour {
    public GameObject LaserBulletPrefab;

	void Update () {
        StartCoroutine(ShootTheThing(5f));
	}

    IEnumerator ShootTheThing(float waitSeconds)
    {
        yield return new WaitForSecondsRealtime(waitSeconds);
        print("Shooting...");
        Instantiate(LaserBulletPrefab, transform.position, transform.rotation);
    }
}

It also prints out “Shooting…” every frame.

The problem is that you are calling StartCoroutine(ShootTheThing(5f)); in your update function. This means that it will be called every frame.

What you need to do is put it on a timer, something like this:

public class shoot : MonoBehaviour {

	public GameObject LaserBulletPrefab;

	void Start() {
		StartCoroutine(ShootLoop(5f));
	}

	IEnumerator ShootLoop(float time) {
		while(true) {
			ShootTheThing();
			yield return new WaitForSecondsRealtime(time);
		}
	}

	void ShootTheThing() {
		print("Shooting...");
		Instantiate(LaserBulletPrefab, transform.position, transform.rotation);
	}
}