Try tostring(plr.UserId)
instead, as a data store key is a string value. There are also 2 problems that end up in studio mode. The first problem is that sometimes, in studio, the player get added after the PlayerAdded event is set up, the solution is to loop through the GetPlayers()
method after setting the event, to not miss any players
local function onPlayerAdded(plr)
...
end
game.Players.PlayerAdded:Connect(onPlayerAdded)
for i, plr in ipairs(game.Players:GetPlayers()) do
onPlayerAdded(plr)
end
Another problem can be that the PlayerRemoving event listener does not finish, and the game shuts down before it finishes, to fix this, you can use game:BindToClose()
, and I use coroutine.wrap()
to save multiple players data at once
local function saveData(plr)
...
end
game.Players.PlayerRemoving:Connect(saveData)
game:BindToClose(function()
for i, plr in ipairs(game.Players:GetPlayers()) do
coroutine.wrap(saveData)(plr)
end
end)
Also, you should wrap your calls with pcall
, otherwise, if the data request errors, it will stop the execution of other code. For more information on saving players data when the server closes, see here.