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 !
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;
}
}
}
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