- Home /
WaitForSeconds not functioning?
Hi all! I am trying to spawn a GameObject every five seconds. I use WaitForSeconds to do this. However, my GameObject is spawned every frame instead. Where is the flaw in my code? Thanks!
You must have something else in Update() calling that routine? Or the while(true) is doing something I've never used? if you are calling that routine from Update(), it will return straight away. The waiting only happens within the routine, so you would normally have something else after the waitforseconds. I would set up a timer in your case, using variables such as spawnTimer = 5, currentSeconds = 0 etc
For this kind of behaviour, I would suggest the following function ins$$anonymous$$d of a coroutine
public void InvokeRepeating(string methodName, float time, float repeatRate);
See doc : http://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.InvokeRepeating.html
Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.
Answer by applemaniac · Jun 18, 2015 at 08:17 AM
You can try that
bool canInstantiate = true
void Start()
{
enemy = ...;
if (canInstantiate)
StartCoroutine(EnemySpawn());
}
IEnumerator EnemySpawn()
{
canInstantiate = false;
Instantiate(......;
yield return new WaitForSeconds(5f);
canInstantiate = true;
}