- Home /
Deleting instantiated prefabs clones?
I need to delete an instated gameObjects clone once I instate it again, for example if a person were to place a block, the next time that person would place that same block the original would become destroyed. How would one do this?? what is the theory behind the code?
I've tried using static variables and some very complex methods to not much avail.
Instantiating and destroying objects is fairly expensive, why not just use the same object again?
That is a good point, you could just have it flying somewhere and then he places the box just give it a new position.
hmm that could do, but I would have to change my code around quite a bit because I'de have to instantiate it the first time :P oh well worth a shot >.<
Answer by Anxo · Nov 21, 2011 at 06:54 PM
When you instantiate the first block give it a a name. Then when you instantiate the second block, check if that name exists, if so delete it and assign the second block to the name.
function PlaceBlock(){
var clone : GameObject;
if(clone!= null){
Destroy(clone);
clone = instantiate.........
}
else
clone = instantiate.........
}
this will give you errors but you get the idea right?
Thanks man, ill try it out, i get the idea behind it. I'm not instantiating my game Object in a function but I think I will move it to one :P ill thumbs up and choose this answer if it works ^^
Hey I got the script working but it's not deleting the clone when there are other clones in play....?
my code is not correct I was just trying to give the idea, clone in destroy for one needs to be clone.gameObject and so on
I know, I did change those things I'm gonna try tagging the clone and destroying it right before the other one instantiates >.<
last attempt worked perfectly! what I did was I took the concept of tagging the box from your previous answer and destroyed the tagged version right before I instantiated it in it's latest form :) thanks for all your help Anxo, it was both your answers combined that got this one solved ^^.
Answer by Anxo · Nov 21, 2011 at 07:05 PM
Anxo's answer is one way to do it. Here is another.
You can give the box a tag, like, "box". Then you create a new script and place it on the box that looks for boxes at the beginning and destroys it.
Like this.
function Awake(){
var oldBox : GameObject = GameObject.FindWithTag("box");
if(oldBox)
{
Destroy(oldBox.gameObject);
}
}
Then every time a new box comes in the scene, it will look for the old box and if there is one it destroys it.
I tried this method as well, it just resulted in me not being able to have any game objects tagged with "box" in play :/
ah yea that makes sense. because It is taged box, remove the tag and add the line gameObject.tag = box at the end of the function, that should fix that.