Hi, I am trying to make a script where it saves the game when you leave. I don’t know why, but UpdateAsync always returns nil. Does anyone know how to fix this? Thanks.
game.Players.PlayerRemoving:Connect(function(player)--PlayerRemoving is when a player leaves.
local playerUserId = player.UserId
local updata = {}
for i, v in ipairs(player.Upgrades:GetChildren()) do
updata[v.Name] = v.Value
end
local success, errormessage = pcall(function()
upgradeData:UpdateAsync(playerUserId, function(oldData)
local previousData = oldData or {DataId = 0}
if updata.DataId == previousData.DataId then
print("then")
else
return nil --It always returns nil
end
end)
end)
end)
I don’t know how, but it worked on another data store I was doing. Can you explain why it works on this one?
Script:
game.Players.PlayerRemoving:Connect(function(player)--PlayerRemoving is when a player leaves.
local playerUserId = player.UserId
local data = {
Cash = player.leaderstats.Cash.Value;
Rebirths = player.leaderstats.Rebirths.Value;
}
for i, v in ipairs(player.CodeStats:GetChildren()) do
data[v.Name] = v.Value
end
local success, errormessage = pcall(function()
myDataStore:UpdateAsync(playerUserId, function(oldData)
local previousData = oldData or {DataId = 0}
if data.DataId == previousData.DataId then
return data
else
return nil
end
end)
end)
end)
The reason why it works there is because you have an IntValue (I assume) named DataId that’s inserted into the table at runtime during the loop, and the value of the IntValue matches either the previous value or the default value of DataId in the function.
Also, if you have two callback functions modifying the player’s data, if one of the them returns nil then the player’s data will likely be erased
for i, v in ipairs(player.CodeStats:GetChildren()) do
data[v.Name] = v.Value
end
is adding values to the data table and one of those values is like an IntValue named DataId that’s being inserted as well. I, of course, don’t have confirmation of this because I don’t know how your game is structured.
At the end of your loop, the table will have a new key named DataId that you’re checking later on:
if data.DataId == previousData.DataId then
return data
else
return nil
end
This is likely why your second script works but the first one doesn’t. Either the first one doesn’t have a key called DataId or the value of DataId is likely a different number