Closest Target Aiming script

Hi y’all! I’m trying to make a rotation/aiming script for my players in a 2D game (hatebin), and so far it’s working! It can detect one enemy automatically and continuously point at it it.

My question is, is there a way to make it so that it can point at the closest tagged player (and change its target accordingly), without modifying much of the code structure?
What I currently think I know, is that I would need to:

a) Make an array of all (P2-tagged) objects in Start(), and

b) Instead of getting the first tagged gameobject it sees as the rotationTarget, use a closestTarget-finder (Finding the vector lengths between the gameobject the script it’s on and the targets, and choosing the one with the shortest one to be rotationTarget/closestTarget I’m guessing) script in Update().

I’m a beginner and did this mostly off of tutorials (Hence why I can’t just go and do it, despite knowing roughly what to do), so basic explanations/tutorials/code would be greatly appreciated.

Any help is more than welcome, thanks!

Since you need to calculate the distance to any potential target anyway, just run the following pseudo code

  • get a list of all potential (tagged) targets, assign the very first target in the list as the “closest one”, and calculate the distance and store it as ‘minDistance’
  • iterate the list (you can skip the first, or start with the first for slightly less performance) as follows: calculate the distance to the currently iterated target, and if that distance is smaller than minDistance, store this as ‘closest one’ and store the distance as the new minDistance

At the end of the loop you automatically aim at the closest target.
Obvious checks: make sure you at least have one (or two) targets.