How do i get the player with the highest value?

So essentially i have an IntValue inside every player and i want to be able to know what player has the biggest value.

Another way to explain this would be to just say how do i know what player has the most cash in a game.

1 Like

This might be a job for Ordered Datastores, i haven’t used it but it is used to make leaderboards and i think there are some good vids on it on youtube.

loop through each player
for example:

local highestvalue = nil;
for i,v in pairs(game:GetService("Players"):GetChildren()) do
    for _,obj in pairs(v:GetChildren()) do
         if obj:IsA("IntValue") then
               if highestvalue == nil then
                     highestvalue = {}
                     highestvalue.Value = obj.Value
                     highestvalue.Player = v
               elseif highestvalue and highestvalue.Value < obj.Value then
                     highestvalue.Value = obj.Value
                     highestvalue.Player = v
               end
         end
    end
end

-- highestplayer variable can be used here

If the intvalue is in directly under the player instance the above script should work.
This script basically just cycles through each player with a table and compares the players’ values.
You can then use the script to get the player object and the intvalue amount they had.

local DataModel = game
local Players = DataModel:GetService("Players")

local function RankPlayers()
	local RankedPlayers = {}
	for _, Player in ipairs(Players:GetPlayers()) do
		local Stat = Player:FindFirstChild("") --Change to name of stat.
		if Stat then
			table.insert(RankedPlayers, {Player, Stat.Value})
		end
	end
	
	table.sort(RankedPlayers, function(Left, Right)
		if Left[2] < Right[2] then
			return Right
		end
	end)
	
	for _, PlayerArray in ipairs(RankedPlayers) do
		local Player = PlayerArray[1]
		local StatValue = PlayerArray[2]
		print(Player.Name, StatValue)
	end
	
	return RankedPlayers
end
1 Like