How do i make a data store for any leaderstats

hi so I’m having trouble making my data store and i wanted to make it compatible for any LeaderStats
i have this datastore script but it sadly doesn’t work

game.Players.PlayerRemoving:connect(function(player)
	local datastore = game:GetService("DataStoreService"):GetDataStore("LeaderStatSave")

	local statstorage = player:FindFirstChild("leaderstats"):GetChildren()
	
	for i =  1, #statstorage do
		datastore:SetAsync(statstorage[i].UserId, statstorage[i].Value)
		print("saved data number "..i)
	end
	print("Stats successfully saved")	
end)

game.Players.PlayerAdded:connect(function(player)
	local datastore = game:GetService("DataStoreService"):GetDataStore("LeaderStatSave")

	player:WaitForChild("leaderstats")
	
	local stats = player:FindFirstChild("leaderstats"):GetChildren()
	for i = 1, #stats do		
		stats[i].Value = datastore:GetAsync(stats[i].UserId)
		print("stat numba "..i.." has been found")
	end
end)

I am having trouble understanding your code

	local statstorage = player:FindFirstChild("leaderstats"):GetChildren()
	
	for i =  1, #statstorage do
		datastore:SetAsync(statstorage[i].UserId, statstorage[i].Value)
		print("saved data number "..i)
	end

StatsStorage would be a table of the children of the Leaderstats but you loop through the table and index UserId

statstorage[i].UserId

Idk if its intentional but I’m pretty sure that’s a major problem

oh what should i do to fix my code

There’s a lot of changes to be made and to be honest I’m unsure where to start because i don’t understand what your trying to achieve when you say…

oh sorry my English is bad, I’m trying to make a script that’s saves my leaderstats data

No, your English was perfect. But now I get what you mean.

You want to save your leader stats within a table right now it looks as if you creating a datastore for each leader state value (which you don’t want to do because datastores can store a lot of data). But not correctly. One moment

loop through every value put it all in a table then use httpservice:JSONEncode() so you only have to save once

yes, that’s what i was trying to say

Get the leaderstats values of each player & then insert them into an array (table) for, 1 array for each player, then just store that table value in the DataStore for each player using the player’s user ID as the key.

some errors in output?and you cant save a lot of values in one datastore(in my mind)

I made a datastore saving system here:

hope it helps!

1 Like