Save a leaderstats (Script)

Fixing


The script is lacking the usage of data stores if you’re looking for stats to be saved across sessions. There appears to be multiple problems at the end, especially dealing with exploits.

game:GetService("Players").PlayerAdded:Connect(function(player)
	local stats = Instance.new("Folder") -- wait why a BoolValue when folders are fine?
	stats.Name = "leaderstats"
	stats.Parent = player
	
	local Points = Instance.new("IntValue")
	Points.Name = "Points"
	Points.Value = 0
	Points.Parent = stats

	local RobuxDonate = Instance.new("IntValue", stats)
	RobuxDonate.Name = "R$ Donate"
	RobuxDonate.Parent = stats

	script.Donate.OnServerInvoke = function(player, amount, recipient) -- this does not work if the script is inside ServerScriptService, remotes should be in ReplicatedStorage
		player.leaderstats.Points.Value = player.leaderstats.Points.Value - amount -- make sure the value does not go negative lol

		local rec = game.Players:FindFirstChild(recipient) -- uh ok
		rec.leaderstats.Points.Value = rec.leaderstats.Points.Value + amount
	end
end)

Saving

Here’s a code sample of saving: The bad method.

local DataStore = game:GetService("DataStoreService"):GetDataStore("cooldatastore")

local saveTable = {}
for _, stat in next, stats:GetChildren() do
	saveTable[stat.Name] = stat.Value
end

DataStore:SetAsync(player.UserId, saveTable)
1 Like

Maybe have a watch of this video by @Alvin_Blox and see if that helps. It pretty much explains out how to save leaderstats values to a datastore.

https://youtu.be/DkYupSBUpes

Yes Alvin Blox is a good coder just the turorial create 2 leaderstats …

1 Like

This script saves the leaderstats?

1 Like

Not quite, updated the post.

Although beware of saving failures and you will need:

  • pcall
  • UpdateAsync over SetAsync
1 Like

I tested and it does not work (it’s a normal script mid-workpace) can you tell me why it does not work?

1 Like

In that case, you are not writing the code correctly:

local Players = game:GetService("Players")

local DataStore = game:GetService("DataStoreService"):GetDataStore("cooldatastore")
local session = {}

Players.PlayerAdded:Connect(function(player)
	local stats = Instance.new("Folder") -- wait why a BoolValue when folders are fine?
	stats.Name = "leaderstats"
	stats.Parent = player
	
	local Points = Instance.new("IntValue")
	Points.Name = "Points"
	Points.Value = 0
	Points.Parent = stats

	local RobuxDonate = Instance.new("IntValue", stats)
	RobuxDonate.Name = "R$ Donate"
	RobuxDonate.Parent = stats

	script.Donate.OnServerInvoke = function(player, amount, recipient) -- this does not work if the script is inside ServerScriptService, remotes should be in ReplicatedStorage
		player.leaderstats.Points.Value = player.leaderstats.Points.Value - amount -- make sure the value does not go negative lol

		local rec = game.Players:FindFirstChild(recipient) -- uh ok
		rec.leaderstats.Points.Value = rec.leaderstats.Points.Value + amount
	end
	
	-- loading
	local success, data = pcall(DataStore.GetAsync, DataStore, player.UserId)
	
	if success then
		if data then
			session[player.UserId] = data -- or set the values of each stat here
		else
			-- default data
		end
	else
		-- error
	end
end)

Players.PlayerRemoving:Connect(function(player)
	local stats = player:FindFirstChild("leaderstats")
	if not stats then return end -- what if it didn't exist first lol

	local saveTable = {}
	for _, stat in next, stats:GetChildren() do
		saveTable[stat.Name] = stat.Value
	end

	local success, errorMessage = pcall(DataStore.SetAsync, DataStore, player.UserId, saveTable)
	if not success then
		-- failed to save
	end
end
1 Like

wat is the "local session = ‘’ " ?

1 Like

i have you code and … image i d’ont have leaderstats

1 Like

Sometimes, I don’t favor keeping the stats in leaderstats. So I always keep a table somewhere around the script to be stored with the data to be saved.

As you can see, the previous script do create memory leak problems due to the fact that the table is filling up as players join. That’s why I have to fix the last block like this:

Players.PlayerRemoving:Connect(function(player)
	local stats = player:FindFirstChild("leaderstats")
	if not stats then return end -- what if it didn't exist first lol

	local saveTable = {}
	for _, stat in next, stats:GetChildren() do
		saveTable[stat.Name] = stat.Value
	end

	local success, errorMessage = pcall(DataStore.SetAsync, DataStore, player.UserId, saveTable)
	if not success then
		-- failed to save
	end

	session[player.UserId] = nil
end

Speaking of which, I’ll re-arrange the code for you in your PMs(although it is not advised to ask for free scripts lol)

1 Like

One warning: Data stores cannot be tested in Studio, unless you have Studio API checked.

Should be looking like this in the settings page:
Enable Studio Access to API Services: [ ]

Else, it will error.

1 Like

I have set true Api services just i d’ont have leaderstats whit you script …
image

1 Like

@Toadiant

The instance is named below the creation of the donate IntValue. The highlighted line of code is bad practice anyway, setting properties after the object’s been attached to the DataModel is inefficient if done where not needed to.


@Operatik

Please don’t put the code that defines the function of Donate.OnServerInvoke in the PlayerAdded event. Every time a player joins, the function gets overwritten with a new one.

Also:

That’s in your recent code. Two lines below it, you parent the value again. Just wanted to point that out for you. :wink:


@Med367367

Just a note that while reading through this thread, you should also be trying to learn and take some lessons from the code you’re getting. Scripting Support is not necessarily a place to ask for free code. There are some issues that you can debug yourself; please don’t copy and paste a script into Studio, then come back without attempting any fixes and say that it’s not working.

Also, in terms of getting leaderstats to show, I think you just need to change the order in which you’re parenting things. Instead of parenting the stats folder immediately after creating it, parent it after you’ve created and parented the rest of your data values.

4 Likes

I do not understand “” Could you (if you do not mind) translate this into “Frentch” because I do not have to understand

Don’t know French myself but I consider Google Translate a great friend. You should be able to get a general idea from this translation:

Notez simplement qu’en lisant ce fil, vous devriez également essayer d’apprendre et de tirer quelques leçons du code que vous obtenez. L’assistance de script n’est pas nécessairement un endroit pour demander un code gratuit. Il existe certains problèmes que vous pouvez résoudre vous-même. veuillez ne pas copier et coller un script dans Studio, puis revenir sans essayer de solutionner et dire que cela ne fonctionne pas.

De plus, s’agissant de l’affichage des dirigeants, je pense que vous devez simplement modifier l’ordre dans lequel vous dirigez les choses. Au lieu de gérer le dossier de statistiques immédiatement après l’avoir créé, parentz-le après avoir créé et parenté le reste de vos valeurs de données.

I tried a different solution before coming on the form I just do not know how to do it anymore

i patch my problem code is
local DataStoreService = game:GetService(“DataStoreService”)
local myDataStore = DataStoreService:GetDataStore(“myDataStore”)

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Points = Instance.new("IntValue")
	Points.Name = "Points"
	Points.Parent = leaderstats
	
	local data
	local success, errormessage = pcall(function()
		data = myDataStore:GetAsync(player.UserId.."-points")
		
	end)
	if success then
		Points.Value = data
else
	print("ERROR DATA NOT SAVED")
	warn(errormessage)
	end
end)
game.Players.PlayerRemoving:Connect(function(player)
	
	local success, errormessage = pcall(function()
		myDataStore:SetAsync(player.UserId.."-points",player.leaderstats.Points.Value)
		
	end)
	if success then
		print("Player data saved !")
	else
		print("Error data not saved")
	end
	
end)

For future posts please follow the guidelines: