Saving multiple values using datastore

ive been trying to save multiple values but only 2 save the 3rd doesn’t work for some reason heres my script

local ds = game:GetService("DataStoreService"):GetDataStore("Data")

game.Players.PlayerAdded:Connect(function(plr)
	local leader = Instance.new("Folder",plr)
	leader.Name = "leaderstats"

	local gems = Instance.new("IntValue",leader)
	gems.Name = "Gems"
	gems.Value = 1
	
	local Cash = Instance.new("IntValue",leader)
	Cash.Name = "Cash"
	Cash.Value = 500
	
	local coins = Instance.new("IntValue",leader)
	coins.Name = "coins"
	coins.Value = 4

	
	local key = "plr-"..plr.userId
	local saveddata = ds:GetAsync(key)

	if saveddata then
	    gems.Value = saveddata[1]
		coins.Value = saveddata[2]
		Cash.Value = saveddata[3]
	else
		local datatosave = {gems.Value, coins.Value, Cash.Value}
		ds:SetAsync(key,datatosave)	
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local key = "plr-"..plr.userId
	local datatosave = {plr.leaderstats.gems.Value, plr.leaderstats.coins.Value, plr.leaderstats.Cash.Value}
	ds:SetAsync(key,datatosave)	
end)
1 Like

Did you print out anything to check if its nil?

It seems there’s a bit of syntax capitalization Issue here do this instead:

local datatosave = {plr.leaderstats.Gems.Value, plr.leaderstats.coins.Value, plr.leaderstats.Cash.Value}

Thanks, but after using the code it still doesn’t work

I don’t know if it will help, but try encoding/decoding the data

local ds = game:GetService("DataStoreService"):GetDataStore("Data")
local HTTPService = game:GetService("HTTPService")

game.Players.PlayerAdded:Connect(function(plr)
	local leader = Instance.new("Folder",plr)
	leader.Name = "leaderstats"

	local gems = Instance.new("IntValue",leader)
	gems.Name = "Gems"
	gems.Value = 1
	
	local Cash = Instance.new("IntValue",leader)
	Cash.Name = "Cash"
	Cash.Value = 500
	
	local coins = Instance.new("IntValue",leader)
	coins.Name = "coins"
	coins.Value = 4

	
	local key = "plr-"..plr.userId
	local saveddata = HTTPService:JSONDecode(ds:GetAsync(key))

	if saveddata then
	    gems.Value = saveddata[1]
		coins.Value = saveddata[2]
		Cash.Value = saveddata[3]
	else
		local datatosave = {gems.Value, coins.Value, Cash.Value}
		ds:SetAsync(key,datatosave)	
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local key = "plr-"..plr.userId
	local datatosave = HTTPService:JSONEncode({plr.leaderstats.gems.Value, plr.leaderstats.coins.Value, plr.leaderstats.Cash.Value})
	ds:SetAsync(key,datatosave)	
end)

Try this Model

SaveStats.rbxm

Put the scripts in ServerScriptService
The DataStore Finds the Childs In Leaderstats, so you can add Multiple Values to the Leaderstat script