How do I autosave data instead of saving only when a player leaves?
Asked by
8 years ago Edited 8 years ago
So I have a script which saves player data whenever the player leaves. But I would want to make it so that it autosaves the data every few seconds. Because when a player leaves, I would be able to call on a function with the parameter of that specific player.
But if I were to make a loop, I will not be able to get each specific name of the players.
I have thought of making a 'LocalScript' which would be imported into every player when they join. And then I would be able to use game.Players.LocalPlayer
to get the specific player. But I want to see if there are other methods of doing this.
My original script is here:
01 | local DSService = game:GetService( "DataStoreService" ):GetDataStore( "DataSaving832723579985723" ) |
03 | game.Players.PlayerAdded:connect( function (player) |
04 | local playerId = "ID-" ..player.userId |
06 | local leaderstats = Instance.new( "IntValue" , player) |
07 | leaderstats.Name = "leaderstats" |
09 | local money = Instance.new( "IntValue" , leaderstats) |
13 | local exp = Instance.new( "IntValue" , leaderstats) |
14 | exp.Name = "Experience" |
17 | local level = Instance.new( "IntValue" , leaderstats) |
21 | exp.Changed:connect( function () |
22 | level.Value = math.floor(exp.Value / 1000 ) |
25 | local HasSaved = DSService:GetAsync(playerId) |
28 | money.Value = HasSaved [ 1 ] |
29 | exp.Value = HasSaved [ 2 ] |
30 | level.Value = HasSaved [ 3 ] |
32 | local toSave = { money.Value, exp.Value, level.Value } |
33 | DSService:SetAsync(playerId, toSave) |
38 | game.Players.PlayerRemoving:connect( function (player) |
39 | local playerId = "ID-" ..player.userId |
40 | local Save = { player.leaderstats.Money.Value, player.leaderstats.Experience.Value, player.leaderstats.Level.Value } |
41 | DSService:SetAsync(playerId, Save) |
I hope someone can give me another idea for this.