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).
1 | local DataStore = game:GetService( "DataStoreService" ):GetDataStore( "Player_Data_WB.PRE-ALPHA" ) |
2 |
3 | game: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) |
9 | 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:
01 | local function OnPlayerRemoving(Player) |
02 | -- save |
03 | end |
04 |
05 | local 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 |
13 | end |
14 |
15 | game.Players.PlayerRemoving:Connect(OnPlayerRemoving) |
16 | 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:
1 | local valuesToSave = { |
2 | wood = stats.wood.Value |
3 | -- continue |
4 | } |