Select enemies with buttons based on their position on scene

Hello. I am creating a top down RPG and need to build an aiming system. I want my character in a battle mode to lock on target and then select between targets on arrow buttons. The select should be performed based on a location and a distance between enemies, that are constantly moving. Like first you select the closest enemy to you, then closest to him and so on. And of course, in a chosen direction. If you have an enemy in front and in back of you, when you press ARROW UP, you should lock on an enemy in front, and when arrow down, then you lock on an enemy in back. If you keep pressing ARROW UP, then you must lock on an enemy that is located upwards from your current selected enemy, and so on. The scene is 3D, and as objects are constantly moving, I am unable to create an array or something. Please, help, I really have no idea of how I can do this.

This solution could be very inefficient depending on how many enemies you have, but first create an array of enemy gameobjects in the scene.

Then, iterate through the array and fire a raycast from your player to the enemy player, and get the distance between them. Add this distance alongside the enemy GO that you hit with the raycast, preferably into a dictionary.

Finally, sort the dictionary by distance to get the GO’s that are closest to you. All this happens in the update, so the enemies can be constantly moving, but you still have a list/dictionary containing the closest enemy GO’s to the player.

Then, by pressing ARROW UP, you can go through the dictionary, highlighting the closest enemies in order.

If you need help coding any of the steps, then ill give it a shot. @Ahronsilv