Hi guys, I'm having a little trouble saving data of players who are the last to leave the session. The code below brings up an error saying that 'player' is a nil value (4th line as seen here).
local DataStore = game:GetService("DataStoreService"):GetDataStore("Player_Data_WB.PRE-ALPHA") game:BindToClose(function (player) local key = "player_"..player.UserId local stats = player.stats --savedValues: {wood, stone, food, gems, gold, premium} local valuesToSave = {stats.wood.Value, stats.stone.Value, stats.food.Value, stats.gems.Value, stats.gold.Value, stats.premium.Value} DataStore:SetAsync(key, valuesToSave) end)
I don't think I can find the UserId of a player who is no longer in the game using this method, what is the best way to get around this problem?
Thank you for your time! :)
The problem is that you assume that game:BindToClose()
is linked to players at all, which it isn't.
This should be how your saving is structured:
local function OnPlayerRemoving(Player) -- save end local function OnGameShutdown() local Players = game.Players:GetPlayers() for Index = 1, #Players do local Player = Players[Index] OnPlayerRemoving(Player) end end game.Players.PlayerRemoving:Connect(OnPlayerRemoving) game:BindToClose(OnGameShutdown)
Additionally, I recommend that you save using a dictionary instead of an array, so it will be easier to modify what exactly you want to save in the future, like this for example:
local valuesToSave = { wood = stats.wood.Value -- continue }