- Home /
Issues with InvokeRepeating in Start/Update functions
I'm still trying to learn Invokes and Coroutines and I think I have them almost down. I have this snippet of code here:
if(distance <= 40)
{
InvokeRepeating ("Spawn", 5, 5);
}
else
{
CancelInvoke ("Spawn");
}
I want to spawn an item once every 5 seconds if I'm within a distance and do nothing if I'm not within distance. I have tried this code in my Start and Update functions.
If in Start, the item is spawned but never stops spawning after I leave the target distance.
If in Update, it works but it Spawns the item every frame creating hundreds of them.
I've also tried using coroutines using this code:
IEnumerator Spawn()
{
yield return new WaitForSeconds(1);
while(true)
{
Instantiate(missile,transform.position,Quaternion.identity);
yield return new WaitForSeconds(randomTime);
}
}
and the calling Start/Stop Coroutine in the if/else statement above but it has the same results.
Can anyone explain how I would achieve what I'm looking for? Thanks
Answer by Landern · Aug 22, 2014 at 05:39 PM
Check to see if it's already invoking, if it is, don't invokerepeating again.
if(distance <= 40 && !IsInvoking("Spawn"))
{
InvokeRepeating ("Spawn", 5, 5);
}
else
{
CancelInvoke ("Spawn");
}
Thanks for the response @Landern, unfortunately this did not work I'm afraid, the items don't spawn at all now in the Update function and when in the Start function, they still spawn even when out of range
Never $$anonymous$$d, I changed the else to an else if and everything works now :) Thanks for the help
Your answer
Follow this Question
Related Questions
Update scene every 5 minutes 2 Answers
How do I replace Invoke Repeating to allow a repeat rate change 1 Answer
convert timer from update() to coroutine or invokerepeating 0 Answers
inconsistent results calculating the distance moved by an object 1 Answer
Script and Start function of script are running, but Update function is not? 0 Answers