Data Persistance is deprecated, use DataStores
With Data Persistance, there isn't a garuntee that your data will be saved. So i'm gonna walk you through how to use DataStores.
With data Stores, you're going to have to know 4 methods.
GetDataStore
- Method of DataStoreService, use it to define the datastore you're using.
GetAsync
--Use it to get the data from a key, will return saved data or nil.
SetAsync
--Use it to save data to a given key.
Update Async
--Use it to update data from a key, second argument is a function that has a parameter of the old data and returns the new data.
So, we want to set up our DataStore.. we use DataStoreService
1 | local ds = game:GetService( 'DataStoreService' ):GetDataStore( "Points" ) |
Next we make a PlayerAdded Event to load any data that could be there, if there is no data then set it to 0
01 | game.Players.PlayerAdded:connect( function (plr) |
02 | local key = tostring (plr.userId).. "_points" |
03 | local data = ds:GetAsync(key) |
05 | local l = Instance.new( 'IntValue' ,plr) |
06 | l.Name = 'leaderstats' |
07 | local p = Instance.new( 'IntValue' ,l) |
Now we have to make sure that data was stored at some point.. so we use a **PlayerRemoving Event* to save data into a key.
01 | game.Players.PlayerRemoving:connect( function (plr) |
02 | local key = tostring (plr.userId).. "_points" |
03 | local stat = plr.leaderstats.Points |
07 | local data = ds:GetAsync(key) |
09 | ds:UpdateAsync(key, function (old) return stat.Value end ) |
11 | ds:SetAsync(key,stat.Value) |
You can read more about DataStores here
You also might want to consider using game.OnClose to set a function that saves everyone's data. in case of instances where your gam may crash or with 1 player servers the server could close before the script saves your data.
So all together?
01 | local ds = game:GetService( 'DataStoreService' ):GetDataStore( "Points" ) |
03 | game.Players.PlayerAdded:connect( function (plr) |
04 | local key = tostring (plr.userId).. "_points" |
05 | local data = ds:GetAsync(key) |
07 | local l = Instance.new( 'IntValue' ,plr) |
08 | l.Name = 'leaderstats' |
09 | local p = Instance.new( 'IntValue' ,l) |
14 | game.Players.PlayerRemoving:connect( function (plr) |
15 | local key = tostring (plr.userId).. "_points" |
16 | local stat = plr.leaderstats.Points |
17 | local data = ds:GetAsync(key) |
19 | ds:UpdateAsync(key, function (old) return stat.Value end ) |
21 | ds:SetAsync(key,stat.Value) |