New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Still have questions? Join our Discord server and get real time help.
0

# How would I get the leader with the most kills in the game?

zomspi 271
14 days ago
Edited 14 days ago

How would I loop through every player in a table then make a variable for the player with the highest amount of kills, and then if someone else overtakes their place the variable changes to that player?

1
Feahren 3662
14 days ago
Edited 14 days ago

You can use the table.sort function. By supplying a predication argument, you can tell table.sort how it should sort the array based on each value compared: a, b. By creating our predication function and filtering with the > greater-than operator, we can organize a table from highest-to-lowest elements.

Assuming you have a Leaderboard containing a Kills ValueObject, we can use it's information as our sort base.

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

local KillsTable = {} do
for _,Player in pairs(Players) do
local Kills = Player:FindFirstChild("Kills")
table.insert(KillsTable, Kills.Value)
end
table.sort(KillsTable, function(a, b)
return a > b
end)
end

print(KillsTable)


Since the first element is the highest, we can find the highest by asking for numerical index one

local HighestKills = KillsTable[1]


This will give us the highest kill-number, but not the player with it, to do that, we can pair the Player with their Kills value in it's own array and store it instead of Kills alone. Since we're inserting a table with two elements, we have to recoordinate the predication function to filter for index 1 to match the Kills properly again.

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

local KillsTable = {} do
for _,Player in pairs(Players) do
local Kills = Player:FindFirstChild("Kills")
table.insert(KillsTable, {Kills.Value, Player})
end
table.sort(KillsTable, function(a, b)
return a[1] > b[1]
end)
end

local HighestKillCount = KillsTable[1][1]
local PlayerWithHighestKills = KillsTable[1][2]

print(PlayerWithHighestKills.Name.." has the highest number of kills: "..HighestKillCount)


Remember to accept this answer if it helps!

0
Well, it is a leaderstat, but an invisible leaderstat called leaderstatsA, also, how do I put all this in 1 script? zomspi 271 — 14d
0
The code above will do everything you need, just change the Kills variable allocation to a leaderstatA ValueObject that handles the Kills Feahren 3662 — 14d
0
So it would be local kills = Player:FindFirstChild("LeaderstatsA"):FindFirstChild("Kills") zomspi 271 — 14d
0
Mhm! Feahren 3662 — 14d