I want only one prefab to be in the scene at once. Each time I make a new one ingame, I want the previous one to be destroyed. How do I get it to check the number of clones in the scene, and only keep the one that was created sooner?
I think this would work. I wrote it so you can have x many clones and if you have one more the first one get's destroyed. In your case this maximum number is one.
var maxNumberOfClones : int;
var location : Vector3;
var prefab : GameObject;
private var numberOfClose : int;
private var activeClones : Array = new Array ();
function Update () {
if (some_condition) { //when do you want to instantiate
activeClones.Add(Instantiate(prefab,location,Quaternion.identity); //at the end of the array, add the newest clone
if(activeClones.length > maxNumberOfClones) { //if there are now to many clones
Destroy(activeClones[0]) //destroy the first entry of the array
activeClones.Shift(); // remove this entry from the array
}
}
}
Keep a reference to the clone when you instantiate it.
var prefab : GameObject;
private var clone : GameObject;
function Spawn () {
if (clone) {
Destroy(clone);
}
clone = Instantiate(prefab);
}