How to keep these values in order in a folder?

I am storing my in-game currency differently and have stored it inside a folder named leaderstats in ServerStorage. The Strength currency is at the top and the Cash currency is below the Strength currency, sometimes when I add a new currency to the folder it jumbles up the currency and places them not in order. Is there a way to place them in order in a folder?

image


TL;DR

To create a functioning leaderboard with stats that won’t change, you need to create a Table of Information; and use that to check if something is getting updated or not. This could then be saved to a Datastore so that way, when people leave the game; their Data can be loaded back in within an instance.


Explained Answer

If you’re creating a leaderboard, you can’t keep them in ServerStorage, they must be placed inside the player when they join. It would be a waste of resources to continuously add in their own separate folder and update it when you believe it needs to be updated.

Instead, you could create a table that gets changed based off what you want.

Here’s an example;

local TableOfInfo = {}

game.Players.PlayerAdded:Connect(function(plr)
	if not TableOfInfo[plr] then
		TableOfInfo[plr] = {
			["Cash"] = 0,
			["Strength"] = 0,
			["Defense"] = 0,
			["User Info"] = {
				["UserId"] = plr.UserId,
				["Username"] = plr.Name,
			}
		}
	end
end)

If you want it to save when they leave the game, you need to create a Datastore and save data into that table when they leave, then when a player joins; have their previously saved data load into the table.


1 Like

They don’t just stay in ServerStorage they are attached to the player when they join. I have made a ModuleScript which has a PlayerAdded function which then is required by a server script and the function activates when the player joins the game. Also, the leaderstats folder is cloned.

1 Like

They just move around like this:

Normal:

image

Changed:

image

Which affects how it appears in-game

1 Like
local function OnStatsChanged(Stat)
	local Stats = Leaderstats:GetChildren()
	table.sort(Stats, function(Left, Right)
		return Left.Name < Right.Name --Sort stats alphabetically.
	end)
	
	for _, Stat in ipairs(Stats) do
		Stat.Parent = nil --Resets stat's 'added' order.
	end
	
	for _, Stat in ipairs(Stats) do
		Stat.Parent = Leaderstats --Places stat back in 'Leaderstats' folder.
	end
end

Leaderstats.ChildAdded:Connect(OnStatsChanged) --'Leaderstats' would be a reference to your 'Leaderstats' folder.
Leaderstats.ChildRemoved:Connect(OnStatsChanged)

Here’s a relatively simple function that will sort your stats alphabetically whenever a stat is added/removed.

2 Likes