Any better way to do this?

So, you might have seen my previous posts about making an RTS.

I have been thinking about for unit targeting and the fog of war just repeatedly check the magnitude between that unit and all enemy units. However, I hate using forever loops, and in a game genre where so many stuff can go wrong, I am wondering if there is a better solution to this.

Note: I’m not asking anybody to write code for me. I just want to know if there is a more efficient way to do this.

Could you provide a lot more info please?

What is your “fog of war”? Are you using large parts to block the view of parts of your map?
Is your world tile-based or something? Are you using ROBLOX’s terrain?
How is this related to unit targeting? Why does the distance between your units and enemy units matter?

What is your actual question?

Well it’s very vague the way you said everything, but there’s one thing I can think of.

Just narrow down when the game should start checking the distances. When the game starts? When a player enters a region3? When a player activates their ability? Just think of how you can narrow things down to when it should start and stop checking the magnitude, to minimize how long the loop is going on for.

Yeah, it’s a good idea to avoid while true do loops in a game, however, this seems to be the best way to handle it since you need to always check for range of detection, plus you can kinda work around the computational cost by using squared distance instead of doing Magnitude from what I have read before.

This is because typically in an RTS you will need raycasting to detect obstacles hiding the enemy and those get pretty expensive if constantly used and if the ray length is long, so a Squared Magnitude check to check if an enemy is in range before detecting obstacles would save performance.

Examples of ray casting for fog of war

Dota 2

Vision - Dota 2 Wiki

Coding challenge obstacle ray casting.
https://www.youtube.com/watch?v=TOEi6T2mtHo

However, as you mention:

This is where the optimization can come in which you will have to start thinking on your own.

Here is my idea, if the enemy unit is all bunched together then you can consider them as a Single Entity so you can treat them as a single enemy unit with a centroid point between all the units, Then do a magnitude check between that enemy of group and your ally group then start doing raycasting.

There are possibly a lot more ways to optimize so the best idea is to just start working on it, and not even the conquerors 3 does fog of war so best luck on your endeavors.