Target nearest enemy wont retarget

97936-gamecode.png

So pretty much I made this code that targets enemies within a 1000 range and this code actually works but with 1 problem, if you move out of range however this code picks 1 enemy forever or atleast until it dies then it picks another one. This means that if you run into another enemy you wont target it unless the first enemy picked is within range.
How do I make it so this code only picks and repicks enemies within range rather than 1 enemy where anywhere in the level.
Any help would be greatly appreciated.

Its really simple you see your code don’t have a sorter, currently your code gets the last actor in the list that in the range of 1000, what you need to add is a sorter for closer to your player, I guess that what you want, what you need to do is to make a Actor Variable (“Closest” or something like that), now just check from the foreach loop with enemy is closer to you, and if the enemy from the loop closer set it to the Variable (“Closest”).
In the end of the foreach loop you have your closest target.

Basically like this (psudocode):

Result = null;
ShortestDist = float.MaxValue;
TargetObjects = [all nearby objects, use sphere overlap]

foreach (Target in TargetObjects)
{
	if (ShortestDist > DistanceToTarget)
	{
		ShortestDist = DistanceToTarget;
		Result = Target;
	}	
}

return Result;

So would I need to add the set actor variable after the forloop? and if so would that variable need to be a array or can it be a single variable?

In the loop body after you check if it closer, it can be single variable I don’t see a reason for an array.