- Home /
Deleting an instance
I am wondering how to delete an instantiate()'d object from inside code. For example, in one object's code, i have
if (Input.GetButtonDown("Shield"))
{
if (shielding == 0)
{
Instantiate(shieldobject,transform.position, transform.rotation);
shielding = 1;
}
} else {
if (shielding == 1)
{
shielding = 0;
}
}
And in my Shield prefab is a code file that goes like this:
function Update () {
if(Input.GetButtonDown("Shield"))
{
Debug.Log("destroyed");
Destroy(gameObject)
}
}
But the shield clone doesn't delete itself. How can i have it delete itself?
Answer by fireDude67 · Jan 17, 2011 at 04:33 AM
When you Instantiate()
an object, you can store it using something like this:
var newObject = Instantiate(shieldobject,transform.position, transform.rotation);
Then later when you want to destroy it, Destroy(newObject)
But with my code as if (Input.GetButtonDown("Shield")) { if (shielding == 0) { var tempshield = Instantiate(shieldobject,transform.position, transform.rotation); shielding = 1; } } else { if (shielding == 1) { shielding = 0; Destroy(tempshield); } } , the shield instance still appears in the Hierarchy as Shield(Clone)...
In your code, 'var tempshield' only exists inside the 'shielding == 0' brace. Declare it outside of there and it should work.
Answer by _Petroz · Jan 18, 2011 at 07:33 AM
Alternatively you could control the destruction from the parent class like this:
var shield : GameObject;
function Update() { if (Input.GetButtonDown("Shield")) { if (!shield) { shield = (GameObject)Instantiate(shieldobject,transform.position, transform.rotation); } } else { if (shield) { Destroy(shield); } }
GetButtonDown only returns true for the frame that the button is first pressed. Your other suggestion duplicates the first answer + comments.
You are right about the GetButtonDown, I removed that part of my post. Although the other person suggested it, $$anonymous$$e is a clearer answer which is the goal of Answers. There is no harm in improving someone else's answer. The goal is to have the best answer not the most original. I also replaced his int with a pointer which is clearer as well.
The compiler says i need a semicolon after the (GameObject) right before the instantiate.
Your answer
Follow this Question
Related Questions
Pass a copy of a GameObject as variable to another script? 1 Answer
How to delete instantiated GameObject 4 Answers
Destroy a specific instantiated clone? 2 Answers
How can I destroy my Instance without renaming it? 2 Answers
Instantiate and Destroy an object while crossing a line with its clone also 1 Answer