How can detect which children has the lowest value

So i’m working on a attack system

and i want to detect which child of a folder has the lowest magnitude ( the closest to your player )

here’s the script

for i,E_unit in pairs(game.Workspace.Units:GetChildren()) do
	local body2 = E_unit.HumanoidRootPart
	local Mag = (body.Position - body2.Position).Magnitude

	for others in pairs(game.Workspace.Units:GetChildren()) do
		local body3 = E_unit.HumanoidRootPart
		local Mag2 = (body.Position - body3.Position).Magnitude
		if Mag < Mag2 then
			local priority = E_unit.Priority
			priority.Value += 1
		end
	end
end

I know this script is unfinished, it’s just that i’m stuck and don’t know how to approach this

3 Likes

so like you want to check what part is the closest?

You only need one loop, you have it almost correct, here is what it should look like

local Mag = 250 --[[ set this to whatever range you want, if the range of the
 nearest humanoid is above 250 then it won't find a nearby humanoid. --]]
local NearestHumanoid


for i,E_unit in pairs(game.Workspace.Units:GetChildren()) do
	local body3 = E_unit.HumanoidRootPart
	local Mag2 = (body.Position - body3.Position).Magnitude -- Assuming body is defined and is the character's humanoid
	if Mag > Mag2 then
		Mag = Mag2
		NearestHumanoid = body3
	end
end
1 Like