Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

?Data Store Wont Work in player

Asked by 6 years ago

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)
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. hiimgoodpack 2009 — 6y

1 answer

Log in to vote
1
Answered by 6 years ago

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)
0
Still doesn't work. goldstorm950 65 — 6y
0
Any errors? iamnoamesa 674 — 6y
0
Nope goldstorm950 65 — 6y
0
Make sure your game permissions allow it iamnoamesa 674 — 6y
Ad

Answer this question