Data saving for multiple leaderstats

So I have this script:

local DSService = game:GetService('DataStoreService'):GetDataStore('Data1')
game.Players.PlayerAdded:connect(function(plr)
	
	local uniquekey = 'id-'..plr.userId
	local leaderstats = Instance.new('IntValue', plr)
	local savevalue =  Instance.new('IntValue')
	leaderstats.Name = 'leaderstats'
	savevalue.Parent = leaderstats
	savevalue.Name = 'Smackouts'
	
	
	local GetSaved = DSService:GetAsync(uniquekey)
	if GetSaved then
		savevalue.Value = GetSaved[1]
	else
		local NumbersForSaving = {savevalue.Value}
		DSService:SetAsync(uniquekey, NumbersForSaving)
	end
end)

game.Players.PlayerRemoving:connect(function(plr)
local uniquekey = 'id-'..plr.userId
local Savetable = {plr.leaderstats.Smackouts.Value}
DSService:SetAsync(uniquekey, Savetable)	
	
	
end)

I’m trying to save 2 leaderstats, one for kills and one for money. Is that possible? I have one script for kills, one script for money and one script for saving kills. I’ve tried to change it many times but it only fails.

1 Like

Try putting it all in one script like this:

local DSService = game:GetService('DataStoreService')
local Data = DSService:GetDataStore("Data")
local Data2 = DSService:GetDataStore("Data2")
game.Players.PlayerAdded:connect(function(plr)
	
	local uniquekey = 'id-'..plr.userId
	local leaderstats = Instance.new('IntValue', plr)
	local savevalue =  Instance.new('IntValue')
    local savevalue2 = Instance.new("IntValue")
	leaderstats.Name = 'leaderstats'
	savevalue.Parent = leaderstats
	savevalue.Name = 'Smackouts'
    savevalue.Value = Data:GetAsync(uniquekey)
    savevalue2.Parent = leaderstats
	savevalue2.Name = 'Name2'
    savevalue2.Value = Data2:GetAsync(uniquekey)
end)

game.Players.PlayerRemoving:connect(function(plr)
    local uniquekey = 'id-'..plr.userId
    Data:SetAsync(uniquekey, plr.leaderstats.Smackouts.Value)
    Data2:SetAsync(uniquekey, plr.leaderstats.Name2.Value)
end)
6 Likes

You can also do it with tables and stuff, I think

2 Likes

Haven’t tried it myself so I didn’t respond with a table.

2 Likes

Yeah, me neither, I just saw it used somewhere.

2 Likes

oh wait, I do have a script that uses tables for datastores although its a little different havent used it for leaderstats.

2 Likes

First off, only use a few keys for saving data. DataStores are pretty mediocre and often can be finicky when saving numerous keys. Save everything under only a few universal keys.

And yes, you can save tables with DataStores. Add your values to a table and then when the player rejoins with the table, reassign the values of the player with the table.

plr.Thing1.Value == savedataepic[1]
plr.Thing2.Value = savedataepic[2]
3 Likes