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

[SOLVED] Why doesn't this cash saving script save the cash?

I created a script to save the amount of cash a player has but it doesn't save the amount of cash they have. How would I fix it to make it work? Here is my code:

local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("CashSaveSystem")

game.Players.PlayerAdded:connect(function(player)
	local leader = Instance.new("Folder")
	leader.Name = "leaderstats"
	leader.Parent = player
	local Cash = Instance.new("IntValue")
	Cash.Parent = leader
	Cash.Name = "Cash"
	Cash.Value = ds:GetAsync(player.UserId)
	ds:SetAsync(player.UserId, Cash.Value)
	Cash.Changed:connect(function()
		ds:SetAsync(player.UserId, Cash.Value)
	end)
end)


game.Players.PlayerRemoving:connect(function(player)
	ds:SetAsync(player.UserId, player.leaderstats.Cash.Value)
end)

5 comments

1

You shouldn't save the cash every time it changes. It's bad practice and can throttle the request limit if saving too often. Only save when they leave, and no need to save it right when they join.

0

I don't know how to do that, could you please show me how?

0

Also, will that fix the script not working?

0

You are already saving when they leave. Just don't save when the cash changes and right after they join.

0

Yeah lol if you keep on saving it, it'll get buggy and break down.

1 answer

✓ Accepted answer

It's because you're saving the cash when the player joins and when changed that can cause the data store to get overloaded so instead you should do

local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("CashSaveSystem")

game.Players.PlayerAdded:connect(function(player)
    local leader = Instance.new("Folder")
    leader.Name = "leaderstats"
    leader.Parent = player
    local Cash = Instance.new("IntValue")
    Cash.Parent = leader
    Cash.Name = "Cash"
    Cash.Value = ds:GetAsync(player.UserId) or 0 --You can change 0 to what ever value you want them to start with if there new
end)


game.Players.PlayerRemoving:connect(function(player)
    ds:SetAsync(player.UserId, player.leaderstats.Cash.Value)
end)

4 comments

0

Also don't forget to publish the game first before testing in studio and don't forget to turn on api services for studio!!

0

It didn't save in studio. I published it then tested it in studio. I edited my cash through the explorer, stop testing and tested it again. It went back to 0.

0

Never mind. I tested it in game and it worked. Thanks!

0

Sometimes it wont work in studio.

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