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

?Data Store Wont Work in player

My data store isn't working for some reason. API services are turned on. It's really weird because if I do something in studio it saves, but it won't save in player, but It will load in player.

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

game.Players.PlayerAdded:connect(function(player)
	local Credits = Instance.new("IntValue",player)
	Credits.Name = "Credits"
	Credits.Value = ds:GetAsync(player.UserId) or 0
	ds:SetAsync(player.UserId, Credits.Value)
	Credits.Changed:connect(function()
		ds:SetAsync(player.UserId, Credits.Value)
	end)

end)


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

1 comment

0

I recommend wrapping anything that has to do with data store in a pcall, as it occasionally errors. You cannot stop these errors, so you should wrap it into a pcall.

1 answer

✓ Accepted answer

There are a few things that you need to change. Firstly, there is no reason to save their stats every time they change. That will cause your server lots of issues.Secondly, SetAsync and GetAsync have a string as their first parameter, not a number(int). Also, you must take account for when the server is closing and the Player Removing event is not fired (This happens when last person leaves the server, or when it is shutdown or crashed for whatever reason.) Taking all that into account, your code should be changed to this:

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

game.Players.PlayerAdded:Connect(function(player) -- Connect, not connect
    local Credits = Instance.new("IntValue",player)
    Credits.Name = "Credits"
    Credits.Value = ds:GetAsync('Player:'..player.UserId) or 0 -- string parameter 
end)


game.Players.PlayerRemoving:Connect(function(player)
    ds:SetAsync('Player:'..player.UserId, player.Credits.Value)
end)
game:BindToClose(function() -- if the last player in the game leaves, don't close the server down until it's saved
	for a,player in pairs (game.Players:GetPlayers()) do
		ds:SetAsync('Player:'..player.UserId, player.Credits.Value)
	end
end)

4 comments

0

Still doesn't work.

0

Any errors?

0

Nope

0

Make sure your game permissions allow it

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