/// <summary> /// Timed deactivation of an instance of this pool for later use. /// </summary> public void Despawn(GameObject instance, float time) { //create new class PoolTimeObject to keep track of the instance PoolTimeObject timeObject = new PoolTimeObject(); //assign time and instance variable of this class timeObject.instance = instance; timeObject.time = time; //start timed deactivation using the created properties StartCoroutine(DespawnInTime(timeObject)); }
//coroutine which waits for 'time' seconds before deactivating the instance IEnumerator DespawnInTime(PoolTimeObject timeObject) { //cache instance to deactivate GameObject instance = timeObject.instance; //wait for defined seconds float timer = Time.time + timeObject.time; while (instance.activeInHierarchy && Time.time < timer) { yield return(null); } //the instance got deactivated in between already if (!instance.activeInHierarchy) { yield break; } //despawn it now Despawn(instance); }