- Home /
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.
Answer by Rugbug_Redfern · Jan 27, 2019 at 05:53 PM
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);
}
}
Your answer
Follow this Question
Related Questions
my script is broken again(enemy refuses to stop seeing me) 1 Answer
Char shots oneside only / kills enemy on specific place. 0 Answers
NullReferenceException on StartCoroutine() 0 Answers
How to temporarily resize a GameObject for a few seconds then revert it back ? 2 Answers
Very basic Instantiate Question 2 Answers