Get nearest entity from table

Im having issues with sorting an array of entities into order from closest to furthest.
Im using this code to get all players in the server

Found = ents.FindByClass("player")

I need to then sort that list from closest to me to furthest from me.
I can’t think of any way other than bubble sorting (This) which i REALLY don’t want to do since this code will be running on tick

Why do you need to sort them every tick?

Also, you need to use


Entity:GetPos and


[editline]23rd July 2017[/editline]

Something like this would maybe suite you, and doing it every tick probably would not be necessary, just call it when you need to check the positions.

local ENTITY = FindMetaTable("Entity")
function ENTITY:GetClosestPlayers()
	local Found = player.GetAll()
	table.sort( Found, function( a, b ) return a:GetPos():Distance(self:GetPos()) < b:GetPos():Distance(self:GetPos()) end )
	return Found

Basicaly what MPan said :slight_smile:

Don’t use

Vector:Distance unless you need the actual value, use

Vector:DistToSqr instead