- Home /
Problem is not reproducible or outdated
Destroy object at the end of a coroutine.
Hi! The problem is following: if I start a coroutine that is supposed to play a dying animation of an object and destroy it I get an error: "Coroutine couldn't be started because the game object ... is inactive!"
Coroutine looks more or less like this:
private IEnumerator Die()
{
StartDyingAnimation();
yield return new WaitForSeconds (2.0f);
Destroy(gameObject);
}
It looks that the error is caused by destroying the object, while the coroutine is still running. Is there a way to call Destroy() inside a coroutine and not trigger that error, or should I move the Destroy call outside of the coroutine?
Yeah you can do both. Remember there is never a wrong answer in C#
You got this.
Answer by NoDumbQuestion · May 23, 2018 at 09:43 AM
If you actually look at the document, Destroy have its own time countdown:
Destroy(gameObject, 2f);
You dont need couroutine.
And also the error you got is couroutine won't call if object is disable (not active, you must have disable object during die animation).
Answer by vinilly · May 23, 2018 at 09:43 AM
Try putting a delay when you destroy the Game Object
Try:
private IEnumerator Die()
{
StartDyingAnimation();
yield return new WaitForSeconds (2.0f);
Destroy(gameObject, 2); // this is for 2 second delay
}
Answer by MaishyN · May 23, 2018 at 10:33 AM
Thanks for the answers! It turned out that it was my stupid mistake - I was accidentally calling the method starting the coroutine twice.
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Coroutine sequence not running properly 1 Answer
Coroutine problems PLEASE HELP ME 1 Answer
My coroutine ends when i initialize a postprocessing setting 0 Answers
iOS bug. transform.translate not working properly only on iOS builds 0 Answers