- Home /
Solved: Destroy command not working
In my FPS, a particle is created at the enemy object's position every time the enemy is shot(which is checked with a raycast). The particle is a prefab that is instantiated, and there is a script attached to it that is supposed to destroy the particle 2 seconds after it is created. Here is the contents of the script(called destroyOverTime):
//Inspector variables
var lifeSpan : float;
function Awake(){
Destroy(this, lifeSpan);}
The variable lifeSpan is set to 1 in the inspector view. However, the particle prefab is never destroyed; each one is always present in the hierarchy. I'm not sure why this is not working, because as far as I can tell the code is correct. Can anyone help? Thanks for your time.
Answer by fafase · Oct 11, 2012 at 06:18 AM
Destroy(this);
means the actual object you are referring to. In this case, the object is the script and not the particle system.
Use `Destroy(gameObject);`
Ok I see. Thanks a lot. Won't it just destroy every instance of that object, though? I need a way of specifically making it destroy that instance of the object.
This is the way. When using gameObject with lowercase g in a script you are referring to the object holding the script. To destroy all similar objects in the scene you first need to find them all with something like:
var array:GameObject[];
array=GameObject.FindObjectsWithTag("Object");
for(var i:int;i<array.Length;i++)Destroy(array[i]);
Notice the Uppercase G on the front meaning you refer to the GameObject class. Then FindObjects is plural meaning you are looking for many instances (maybe only one or even none). Then the for loop iterates through the array and destroy the corresponding object.
Ah, okay. I really hate how simple and kind of obvious everything is once its explained to me. Haha