How can I find out which value is the least?

Hello fellow developers, I am making a script that allows me to find the closest player to someone, teleport to them and attack them and I’m still stuck on the first part. My idea is to use magnitude obviously, I want to get every player in a 60 stud radius, put each magnitude and player in a table and sort the magnitudes out least to greatest and teleport to the player with the closest magnitude from the user, I’ve tried table.sort but I’m not sure how to use it in this situation, any help is appreciated and have a great day!

Have you tried this?

table.sort() takes a second argument other than the table you want sorted. This second argument is a function which returns a true/false value. The parameters of this function are the elements of the table being sorted, or as named in my sample code, targetA and targetB. If the function returns true, targetA will go before targetB in the table. If false, then targetB goes before targetA.

local myChar; --Assign this accordingly.
local targets = {workspace.Dummy1, workspace.Dummy2, workspace.Dummy3};

function sort(targetA, targetB)
	local targetADist = (myChar.HumanoidRootPart.Position - targetA.HumanoidRootPart.Position).Magnitude;
	local targetBDist = (myChar.HumanoidRootPart.Position - targetB.HumanoidRootPart.Position).Magnitude;
	return targetADist < targetBDist;
table.sort(targets, sort);

I’m not too confident in my explanation, so I advise you to read this if you’re still unsure of how table.sort() works.

1 Like