- Home /
Destroy Instantiated GameObject Problem
Ok so I'm pretty sure my problem is I'm not using the correct syntax for telling the Destroy command what to actually destroy. I'm just putting a small snippet of the script up because the rest is really unnecessary. The "shotgunShootParticle" variable is a GameObject. Really my only problem is figuring out how to destroy the instantiated object.
function Update(){
if(Input.GetButtonDown("Fire1")){
Instantiate(shotgunShootParticle, transform.position, transform.rotation);
Destroy(shotgunShootParticle, 1);
FireWeapon();
}
}
What is the problem you have with the function? Do you get a error message or anything?
Because using the Destroy-function should be enough to destroy you gameobject.
The function you have above waits for 1 second before its destroyed, The actual destruction of the object is delayed to after the engine update call is finished.
But I noticed that you don't keep the instantiated object, and you are destroying the orginal object. $$anonymous$$aybe you rather want to destroy the newly instantiated object?
Another thing, what you can also do, is something like this to make sure that the object actually do exist:
newCreatedShotgunparticle = (GameObject)GameObject.Instantiate(shotgunShootParticle, transform.position, transform.rotation);
if(newCreatedShotgunparticle != null)
{
Destroy(newCreatedShotgunparticle, 1);
}
But using instantiate in game-mode is not recommended. Try to use a pre-created pool of shotgunparticles ins$$anonymous$$d.
Read more here: http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html
Good luck!
Answer by fafase · Nov 29, 2012 at 07:00 AM
Two solution to your problem:
first: When you destroy an object you need a reference, you do not have any there.
var myRef = Instantiate(shotgunShootParticle, transform.position, transform.rotation);
Destroy(myRef, 1f);
Second solution is to simply tick OneShot in the particle system. That will automatically destroy the object.If you are using shuriken tick off Looping.
Thank you sir! Sorry I didn't accept this answer sooner! I feel so rude I implemented your solution a long time ago! Going back through all my questions right now and giving people their due justice.