Detecting a gameObject has been destroyed inside a trigger

Hi there!

I’m pretty new to Unity, C# and coding in general. I’m making a game that looks like a Plant Vs. Zombie and I’m at the point where I need my defenders to detect if there’s some attackers in their lane, and start firing when it’s the case, and stop when there’s no Attackers left or the attackers are behind them.

I need to know when an enemy has died (been destroyed) in a script that manages everything going on on the play field. I want to be able to set a public GameObject deadEnemy, which is a reference to the more recent dead enemy, to be able to pass it to my attacker so he can remove it from its list of validTargets.

My problem is that I though I could do it with a OnTriggerExit2D(), but the Attacker does not seem to trigger that function when it gets destroyed. I understand the “why” it does not do so, but I need an alternative to find that the Attacker has been destroyed so I can update it as my most recent dead enemy.

Thanks a lot!

Joey

Depending on how you have the project set up, you could in theory just set the enemy that is dying to that deadEnemy var, then call it to be taken from the list, then destroy the object.

Leave OnTriggerExit to handle all enemies that are alive and passing the “behind” of the “tower”, same principles as above.