I took a big break from coding and just got back. I am trying to make a table with all the players stats in the datastores. But for some odd reasons, I’m unable to set anything to the datastores.
Here is the snapet of code that I took from the API:
local DSS = game:GetService("DataStoreService")
local dataStore = DSS:GetDataStore("PlayerData")
function fetchPlrData(plr)
local success, data = pcall(function()
dataStore:GetAsync(plr.UserId)
end)
print(plr.UserId,data)
end
function setPlrData(plr)
local success, errorMessage = pcall(function()
dataStore:SetAsync(plr.UserId,10)
end)
print(plr.UserId)
end
game.Players.PlayerAdded:Connect(function(plr)
local plrData = fetchPlrData(plr)
if not plrData then
plrData = {Experience=0,Money=0}
end
local statsClone = statsFolder:Clone()
statsClone.Parent = plr
statsClone.Experience.Value = plrData.Experience
statsClone.Money.Value = plrData.Money
end)
game.Players.PlayerRemoving:Connect(function(plr)
setPlrData(plr)
end)
game:BindToClose(function()
wait(1)
end)
This is the output:
00:13:42.745 1360353834 nil - Server - Script:9
00:13:48.307 Disconnect from ::ffff:127.0.0.1|60106 - Studio
00:13:48.666 1360353834 - Server
And I did turn on Studio Access to API services.
Data is fetched upon entering the game and saved when leaving. I also added a BindToClose timer to give time to the script to save the datastore
Wow im lost. I removed the return to do some testing, but now that you asked, it works when I add it back! I have no idea what went wrong and whats different between having return or not but it worked. Thanks
function fetchPlrData(plr)
local success, data = pcall(function()
return dataStore:GetAsync(plr.UserId)
end)
end
function setPlrData(plr)
local data = {plr.leaderstats.Experience.Value,plr.leaderstats.Money.Value}
print(data)
local success, errorMessage = pcall(function()
dataStore:SetAsync(plr.UserId,data)
end)
if not success then
print(errorMessage)
end
end
Now when I try to add a table to save in the datastore, it always reads as nil.
print(data)
local success, err
local tries = 5
repeat
success, err = pcall(function()
allDataStore:SetAsync("User_"..plr.UserId, data)
end)
tries -= 1
if not success then
warn(err)
task.wait(2)
end
until success or tries==1
if not success then
warn("Unable to save data of "..plr.Name)
end
So I have this DataStore setup that tries saving multiple times when a player leaves in case it accidentally errors. I’m not sure if this setup would solve your problem but it solved mine when my data would sometimes not save.