The question is answered, right answer was accepted
finding valid targets in range
in my game the player has a melee attack. At the moment the way i check for valid targets is the following. But how do i remove dead/destroyed stuff from the list? And is there maybe a better alltogether to find valid target in a certain range? Maybe a way without a triggerCollider (no clue how to do that, though)
void OnTriggerEnter2D (Collider2D other){
BaseShotableObject v = other.GetComponent<BaseShotableObject> ();
victims.Add (v);
Debug.Log ("entered in melee" + v.ToString());
}
void OnTriggerExit2D (Collider2D other){
BaseShotableObject v = other.GetComponent<BaseShotableObject> ();
victims.Remove (v);
}
Answer by eatsleepindie · May 02, 2016 at 08:32 PM
You could add a boolean to the BaseShotableObject component for tracking whether the object is dead/destroyed. Then your first function would look like this:
void OnTriggerEnter2D (Collider2D other){
BaseShotableObject v = other.GetComponent<BaseShotableObject> ();
if(v.IsDead)
return;
victims.Add (v);
Debug.Log ("entered in melee" + v.ToString());
}
that wouldnt work. When it enters the Trigger its still alive ( else it couldnt enter the trigger) v dies AFTER it beeing attacked, which requieres v to be in the victimslist for at least 1 attack.
Now if kill it , it cant send a triggerExit, since its destroyed therefore stays in the list forever.
Beside: you cant call a method or bool of a destroyed object.
I assumed when you said death/destroy that you weren't literally destroying the game object, my mistake.
You could use the OnDestroy method on each object to check if it is in the victims list and then remove it the same as you do in OnTriggerExit2D.
http://docs.unity3d.com/401/Documentation/ScriptReference/$$anonymous$$onoBehaviour.OnDestroy.html