- Home /
Have gameObjects destroy themselves from external script
I am making a game that will randomly spawn characters (like in a tower defense game) that will go through a path and then either die or reach a given finish. Once a character is instantiated I add a script as a Component to that character that works as a controller for that specific character. The idea is that the characters are given a random route, all of which have their own specific instructions regarding how to maneuver through the course. When the unit is either dead or reaches the finish I want it to Destroy itself. Is there any smart way I can either pass the gameObject as a variable to the controller script so I can use Destroy(gameObject) or any other way to easily delete the units that are supposed to be removed?
Answer by Jeff-Kesselman · May 08, 2014 at 08:15 PM
In any monobehaviour, or sub-class thereof, the variable gameObject is a reference to the owning object.
See https://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.html for everything available within a component.
Answer by robinrei · May 08, 2014 at 10:18 PM
You could simply do the following in the controller script that you are attaching to the characters:
if(_hasReachedGoal || _hasDied)
{
GameObject.Destroy(gameObject);
}
Answer by thooom · May 18, 2014 at 07:08 PM
I solved this by creating a function like this.
function destroyCar(carToDestroy : GameObject) { while(carToDestroy.transform.position.y > -5 && carToDestroy.transform.position.y < 5.5 && carToDestroy.transform.position.x < 10 && carToDestroy.transform.position.x > -10)
{ yield WaitForSeconds(0.5); }
Destroy(carToDestroy); }
I then run this script right after I instantiate an object while I have it accessible by running
destroyCar(carName);
Answer by screenname_taken · May 18, 2014 at 06:53 PM
Why not a trigger box at the end with the Destroy(...) instruction if the object that enters said trigger box matches with your enemy tag?