How do I automatically target a random enemy within a certain range and switch targets when it dies?

In my game, you control a tank, and you have two guns, one which is aimed by you, the player, and one which automatically aims at an enemy within range. All of my enemies are tagged Enemy. I want the second gun to rotate towards a random enemy within range, and not choose a new target until it’s dead. If more information is needed, let me know, because I have no idea what would be helpful.

well, you can try doing this:

1- create an empty game object under your player and attach a collider to it (set “isTrigger” to true).

2- adjust the size of the collider to match the range you want.

3- attach a script that contains an OnTriggerEnter function.

4- in the function check if the object entering the trigger has an enemy tag.

5- if it does, store a reference to it in a list.

6- make another function that assigns the current target from the list at random.

7- in your update loop keep checking if that target still exists (I’m assuming once it dies you’ll destroy the object and the reference will become null.

8- once the reference is null call the function in step 6 again.

it’s just a high-level overview of what you can do. Lmk if you need more clarification