- Home /
Keep doing Coroutine even when destroy game object ??
Hello ! Is there anyway to keep doing coroutine even when destroy object ??? I want my Enemy destroy first, then after 1s I destroy my effect that link to Enemy ??? Thanks for advice !
Answer by unityBerserker · Sep 11, 2019 at 10:52 AM
Invoke coroutine from another script. I usually use the couroutine manager, which is attached to the always active gameObject. Below is the CoroutineManager script. Add it to the always active gameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoroutineManager : MonoBehaviour
{
static CoroutineManager instance;
public static CoroutineManager Instance { get { return instance; } }
private void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
}
else
{
instance = this;
}
}
}
I created a sample script showing that coroutine will be executed correctly even after destroying the object.
Add the Example script to some gameObject. This gameObject will be destroyed after 1 second. Assign another gameObject to the "efect" field. This gameObject will be destroyed after 2 seconds.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
// reference to "efect" I want to destroy
public GameObject efect;
void Start()
{
//we call ExampleCoroutine and pass references to gameObject "efect".
CoroutineManager.Instance.StartCoroutine(ExampleCoroutine(efect));
// after 1 second gameObject with this script will be destroyed
Destroy(this.gameObject,1);
}
IEnumerator ExampleCoroutine(GameObject efect)
{
yield return new WaitForSeconds(2);
// after 2 second we destroy "efect"
Destroy(this.efect);
while (true)
{
// we display log to show that coroutine is living
Debug.Log("I live!");
yield return null;
}
}
}
@unityBerserker I'm having a similar issue I need to figure out. What if the game object that doesn't get destroyed is a prefab that will be duplicated a bunch? This solution probably won't work for me. I opened a question about this if you would like to look at my issue.
Answer by Pangamini · Sep 11, 2019 at 11:28 AM
The @unityBerserker's answer is good. But if all you need is to destroy an object with a delay, you can simply call Destroy(this.effect, 1f); It's a built-in delayed destroy
Your answer
Follow this Question
Related Questions
Destroying an object with running coroutine 2 Answers
How to destroy children one after another in a coroutine, but with a for loop. 1 Answer
DisplayText info and wait for animation ends to destroyobject ( time extra box) 0 Answers
How to use corutines in a class 1 Answer
How to start a coroutine from Update. 4 Answers