Hello, so, this is my data saving script:
local ds = game:GetService("DataStoreService")
local data = ds:GetDataStore("Data")
local function saveData(plr)
local saveTable = {}
saveTable.Values = {}
for _, v in pairs(plr.playerValuesToSave:GetChildren()) do
saveTable.Values[v.Name] = v.Value
end
data:SetAsync(plr.UserId, saveTable)
end
local function loadData(plr)
local saveTable = {}
local succ, err = pcall(function()
saveTable = data:GetAsync(plr.UserId)
end)
if succ then
return saveTable
else
return err
end
end
game.Players.PlayerAdded:Connect(function(plr)
local values = script.Values
local playerValues = Instance.new("Folder")
playerValues.Parent = plr
playerValues.Name = "playerValuesToSave"
local playerData = loadData(plr)
for _, v in pairs(values:GetChildren()) do
local readyValue = v:Clone()
readyValue.Parent = plr.playerValuesToSave
if playerData and playerData.Values then
readyValue.Value = playerData.Values[v.Name]
elseif playerData == nil then
saveData(plr)
end
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
saveData(plr)
end)
And I’m having an issue with it, can anyone tell me why it’s not saving data? It isn’t throwing any kind of error, either.
1 Like
As far I understood Datastores you can’t store tables but you can convert them to JSONs with HTTPService. I Simply do the following to convert it into a JSON string.
HttpService:JSONEncode(saveTable)
And to convert it back to a table back I just simply do
HttpService:JSONDecode(savedData)
Actually you can store tables in data store…
Try doing game:BindToClose()
like this:
game:BindToClose(function()
for i,v in pairs(game.Players:GetPlayers()) do
saveData(v)
end
end)
(Logically you can keep the player removing.)
All data passed into a datastore will be JSONEncoded anyways. Doing it twice is useless.
Nope! That isn’t true at all, I already have a table saving system, I’m just trying to make one with i, v in pairs so it’s more efficient.
Thank you, too! However, the BindToClose solution worked too.
Thank you for the solution!
30charssssss
I don’t really find any error in your script. But, I think I know why.
PlayerRemoving event defines the moment when a player has left, not before it,
so when you try to get his data the player is no longer in the game.
But there’s something to deal with it.
BindToClose is the answer. It is an event which fires each time the player is about to leave, these few seconds whenever the player for example is closing the game by pressing ‘X’ etc.
So, you better use this so you’ll still have access to the data since the player will still be in in those few seconds. Here’s a very short example of how to use this event:
game:BindToClose() = function()
--Code inside of here.
end)
I hope I helped you. Feel free to message me for further questions.
Thanks,
XDvvvDX.