Creating a Leaderboard
Creating a Leaderboard
Problem
You want to create a leaderboard in which you can change points and such.
Solution
Create a “leaderstats” directory and place all values within IntValues.
game.Players.PlayerAdded:connect(function(player) local leader, score = Instance.new('IntValue'), Instance.new('IntValue') leader.Name = 'leaderstats' score.Name = 'Score' score.Parent = leader leader.Parent = player end)
Discussion
We first connect the PlayerAdded event, so when a Player enters the game, this code will fire. We create two IntValues which are assigned to leader
and score
. An IntValue is an object that just holds an integer. To change the Value of an IntValue you use IntValue.Value
. Notice that we pass Instance.new
a second argument, player
. The second argument to Instance.new
parents the newly created instance to that argument.
Then we set the name of the first IntValue to be leaderstats
. Roblox itself will look into the Player directory and if it finds the leaderstats
, it will use that for its actual leaderboard (the in game GUI where you see all the player names, and KOs and WOs if applicable). We then name the second IntValue Score
and parent it to the leaderstats
.
A good question would be… “Why didn’t we just do local leader, score = Instance.new('IntValue', player), Instance.new('IntValue', leader)
. We did it for the leaderstats
, why did we use the long way for the Score
?”. The Lua language itself simplifies all values before it assigns them. Therefore it would try to evaluate Instance.new('IntValue', leader)
before leader
would be existed. Therefore, we cannot use the shortcut in a multiple variable declaration. We could however do this:
game.Players.PlayerAdded:connect(function(player) local leader = Instance.new('IntValue') local score = Instance.new('IntValue') leader.Name = 'leaderstats' score.Name = 'Score' score.Parent = leader leader.Parent = player end)
Since we already finished defining leader
, we could then use it in a second variable declaration.