Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make this leaderstats script save to the Datastore?

I have a script in one of my games that handles money being given out every 5 minutes, and I need it to save to the datastore so when the player rejoins the game after buying/earning the money they keep it, instead of their money counter resetting.

The code is here to help you understand what I am talking about:

game.Players.PlayerAdded:Connect(function(Plr)
	local Stats = Instance.new("Folder", Plr)
	Stats.Name = "leaderstats"
	
	local Cash = Instance.new("IntValue", Stats)
	Cash.Name = "Cash"
	Cash.Value = 0
	
	local DS = game:GetService("DataStoreService")	
	
	game.Players.PlayerRemoving:Connect(function()
		DS:SetAsync(Plr.userId.."_DS", Cash.Value)
	end)
	
	while true do
		wait(300)
		for i, v in pairs(game.Players:GetPlayers()) do
			v.leaderstats.Cash.Value = v.leaderstats.Cash.Value + 100
		end
	end
end)

As you can see in the script above I tried getting an understanding of the Datastore service

	local DS = game:GetService("DataStoreService")	
	
	game.Players.PlayerRemoving:Connect(function()
		DS:SetAsync(Plr.userId.."_DS", Cash.Value)
	end)

But, that did not work. Could I get some help on this?

1 comment

0

You never actually retrieved and set their data. Read the GlobalDataStore documentation or watch a tutorial, preferably by TheDevKing.

1 answer

✓ Accepted answer

YOU NEED TO COPY THIS ALL DOWN. SOME OF IT WONT COME UP AS A SCRIPT BUT COPY AND PASTE THIS ALL INTO A NEW SCRIPT IN SERVER SCRIPT SERVICE

local DS = game:GetService("DataStoreService"):GetDataStore("SaveData") game.Players.PlayerAdded:Connect(function(plr) wait() local plrkey ="id_"..plr.userId local save1 = plr.leaderstats.Kills

local GetSaved = DS:GetAsync(plrkey)
if GetSaved then
	save1.Value = GetSaved[1]
else
	local NumberForSaving = {save1.Value}
	DS:GetAsync(plrkey, NumberForSaving)
end

end)

game.Players.PlayerRemoving:Connect(function(plr) DS:SetAsync("id_"..plr.userId, {plr.leaderstats.Cash.Value}) end)

1 comment

0

Amazing! Thanks for the code, Datastore on roblox has always stumped me. Excellent work!

This discussion is preserved as it was. New answers, comments, and votes are closed.