- Home /
Destroy cancels InvokeRepeating?
Does it not matter what order/where you put Destroy? I have this code
if (touched==1)
{
audio.PlayClipAtPoint(gemgotsound,transform.position);
InvokeRepeating("gotonextlevel",1.5,1);
Destroy (this.gameObject,0.1);
}
The sound plays fine. But the InvokeRepeating only works if I comment out Destroy (gameObject)? Even if I set Destroy to happen after a time period, it still doesn't work. I could think of some ugly coding methods to deal with this, but what is the elegant solution?
Answer by jorjdboss · Aug 27, 2012 at 08:32 AM
I don't know what you're trying to do exactly by calling InvokeRepeating() to switch levels. If you destroy the gameobject, all attached components will also be destroyed. Since the function gotonextlevel() resides in the same script which is a component of the main gameobject, Invoke repeating wont work anytime after the gameobject is destroyed. The function gotonectlevel() will be called once and thats all. Would be helpful if you mentioned why exactly you're calling InvokeRepeating() to switch levels.
Yeah, I latter realised - I was thinking it was a function that should just be called and do it's thing - I forgot it's thing is to call another function that's inside what is being destroyed. I'm using invoke because I want the level to end a second or so after the gem is collected, not at the very instant it's collected. I may delete this question if it's not a very good one.
Did you know that if you're using Application.LoadLevel(), all the gameobjects in the current scene are destroyed before the new level is loaded?
By the way, your problem can be solved easily:
if (touched==1) { audio.PlayClipAtPoint(gemgotsound,transform.position); StartCoroutine(waitAndLoadLevel()); }
IEnumerator waitAndLoadLevel() { yield return new WaitForSeconds(3); // waits 3 seconds and then loads level gotonextlevel(); // assu$$anonymous$$g that you do Application.LoadLevel() inside gotonextlevel() Destroy (this.gameObject,0.1); }
Yeah, I'm fine with everything being destroyed. I don't actually want the repeating part - I just want that I can put a delay in by using it. I will try your code at some point, though the formattings been lost. I made up something that works, but yours is certainly tighter looking code. Thanks.