Question by
eleniondil · Oct 25, 2017 at 01:42 PM ·
timerinstantiate prefabdestroy objectdestroy-clones
How to destroy the most ancient clone?
I'm spawning multiple clones from random prefabs. It works perfectly as intended if the 'spawntime' is bigger than 'lifetime'. But if 'lifetime' is bigger than 'spawntime' and multiple clones of the same prefab spawn, it looks like the old clones 'lifetime' reset as soon as the new clone is created.
Is there a way for it to not happen? So that each clone has his own 'lifetime' that never reset. Thanks.
using UnityEngine;
using System.Collections;
public class Pill : MonoBehaviour
{
public Rigidbody2D bonus1;
public Rigidbody2D bonus2;
public float spawntime = 2.0f; //new clone every x second
private float respawn;
public float lifetime = 5f; //clone dies after x seconds
void Start ()
{
respawn = spawntime;
}
void Update ()
{
respawn -= Time.deltaTime; //timer
if(respawn <0)
{
int rand = Random.Range(1,2); //select bonus pill randomly
if(rand == 1) {
Instantiate(bonus1, new Vector3(Random.Range(-8.0f, 8.0f), Random.Range(-4.0f, 4.0f), 0), Quaternion.identity); //create bonus pill 1
Destroy(GameObject.Find("bonus1(Clone)"), lifetime); //destroy after its lifetime
}
if(rand == 2) {
Instantiate(bonus2, new Vector3(Random.Range(-8.0f, 8.0f), Random.Range(-4.0f, 4.0f), 0), Quaternion.identity); //create bonus pill 2
Destroy(GameObject.Find("bonus2(Clone)"), lifetime); //destroy bonus5 after its lifetime
}
respawn=spawntime; //reset timer
}
}
}
Comment
Your answer
Follow this Question
Related Questions
destroy prefab over time 0 Answers
Destroying Instantiated Prefab in Another Script -- Can't destroy to prevent memory loss? 0 Answers
[Beginner] Growing Fruits on Trees. 0 Answers
My Timer instance is not destroying itself and isn't even counting properly. 0 Answers
Objects are not getting destroyed [I fixed on my own] 1 Answer