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?
In any monobehaviour, or sub-class thereof, the variable gameObject is a reference to the owning object.
See Unity - Scripting API: MonoBehaviour for everything available within a component.
You could simply do the following in the controller script that you are attaching to the characters:
if(_hasReachedGoal || _hasDied)
{
GameObject.Destroy(gameObject);
}
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);
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?