Array Problems, Tower Defence Game

Hi unity

I am developing a Tower Defense game. The problem I have ran into, is the turret shooting que. I would like the turret to shot at the first object that enters its trigger via, OnTriggerEnter. Then after that target dies or leaves, to switch to the next one behind it.

I was thinking on making a variable inside the “Enemy” that when it hits the collider to start a timer inside it’s script. += Time.deltaTime;

The turret would have a array storing all the enemies that entered it’s collider (Add). When a target died or left the collider the turret would loop the array length and find the enemy inside the collider with the greatest value of the timer and pick it as its next target.

I would like to do it this way because then, I would be able to make my turrets have options in what targets to target next using this same method. Ex, highest health, lowest health, fastest speed, Etc.

Ive been trying to get this to work with arrays for a few days now but nothing i do works. I get nulls when trying to remove a element in a array, when the enemy dies in the trigger it dosn’t register as OnTriggerExit, and it goes on.

If this is not possible? Could someone point me to a way that is.
My scripting isn’t the best as I am still learning. Spoon feeding needed on this one.

james

As few others suggested using a List is the best way to go.

This is how I did this sometime back.

I would give unique id to the enemy. When you instantiate an enemy add enemy object to a dictionary indexed by the enemy id. When enemies die or exit game remove them from this dictionary. Maintain this dictionary outside the towers.

In OnTriggerEnter in tower I simply add this unique id to a list maintained on the tower. At OnTriggerExit I remove the id from the list.

When the tower wants to attack it will get the id from its list and get the actual object from your main enemy dictionary.

The advantage of this method is that you maintain only a list of ids not actual objects on the tower. Also now you have a list of enemies in the game at a given time so you can use that for other things.