- Home /
Destroy all previous clones.
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?
Answer by Joshua · May 01, 2011 at 05:07 AM
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
}
}
}
This goes on the prefab, right? And I'm guessing I need to fill in some of those variables.
No, this goes anywhere but those prefabs, because those will get destroyed and you only want one version of this script to run at a time. Just put it on your main camera or something else you won't destroy. And yes, you have to fill in the blanks.
I don't understand what to put in the if statement, or what I'm supposed to do with the "location".
When do you want to instantiate? Leave the whole if statement out to instantiate every frame. But put, for instance, Input.Get$$anonymous$$ouseButtonDown(0) in there to only instantiate when you click your mouse. It's just an empty placeholder :)
Answer by Eric5h5 · May 01, 2011 at 05:45 AM
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); }
Damn you for your simplicity! But my script works for any maximum number of clones ^.^ so hah :p