Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

:BindToClose() datastoreing question (?)

Asked by 6 years ago

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).

1local DataStore = game:GetService("DataStoreService"):GetDataStore("Player_Data_WB.PRE-ALPHA")
2 
3game:BindToClose(function (player)
4    local key = "player_"..player.UserId
5    local stats = player.stats
6    --savedValues: {wood, stone, food, gems, gold, premium}
7    local valuesToSave = {stats.wood.Value, stats.stone.Value, stats.food.Value, stats.gems.Value, stats.gold.Value, stats.premium.Value}
8        DataStore:SetAsync(key, valuesToSave)
9end)

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! :)

1 answer

Log in to vote
3
Answered by
Avigant 2374 Moderation Voter Community Moderator
6 years ago

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:

01local function OnPlayerRemoving(Player)
02    -- save
03end
04 
05local function OnGameShutdown()
06    local Players = game.Players:GetPlayers()
07 
08    for Index = 1, #Players do
09        local Player = Players[Index]
10 
11        OnPlayerRemoving(Player)
12    end
13end
14 
15game.Players.PlayerRemoving:Connect(OnPlayerRemoving)
16game: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:

1local valuesToSave = {
2    wood = stats.wood.Value
3    -- continue
4}
Ad

Answer this question