I spawn object that must be deleted after a time intervalue. But sometimes the object should stay. Is there any way to cancel the Destory(GameObject, time) method?
1 Answer
1No, but you can use a coroutine and cancel the coroutine, which is what I guess Destroy does behind the scenes.
void Start()
{
//start the countdown
StartCoroutine( "DestroyAfterTime", 10f );
}
IEnumerator DestroyAfterTime( float t )
{
yield return new WaitForSeconds( t );
Destroy( gameObject );
}
void Update()
{
//I decide I want to cancel it
StopCoroutine( "DestroyAfterTime" );
}
It would be cleaner to use Invoke/CancelInvoke; it's unlikely that Destroy uses a coroutine.
– Eric5h5