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
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
game.Players.PlayerAdded:connect(function(plr)
local key = tostring(plr.userId).."_points"
local data = ds:GetAsync(key)
data = data or 0
local l = Instance.new('IntValue',plr)
l.Name = 'leaderstats'
local p = Instance.new('IntValue',l)
p.Name = "Points"
p.Value = data
end)
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.
game.Players.PlayerRemoving:connect(function(plr)
local key = tostring(plr.userId).."_points"
local stat = plr.leaderstats.Points
local data = ds:GetAsync(key)
if data ~= nil then
ds:UpdateAsync(key,function(old) return stat.Value end)
else
ds:SetAsync(key,stat.Value)
end
end)
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?
local ds = game:GetService('DataStoreService'):GetDataStore("Points")
game.Players.PlayerAdded:connect(function(plr)
local key = tostring(plr.userId).."_points"
local data = ds:GetAsync(key)
data = data or 0
local l = Instance.new('IntValue',plr)
l.Name = 'leaderstats'
local p = Instance.new('IntValue',l)
p.Name = "Points"
p.Value = data
end)
game.Players.PlayerRemoving:connect(function(plr)
local key = tostring(plr.userId).."_points"
local stat = plr.leaderstats.Points
local data = ds:GetAsync(key)
if data ~= nil then
ds:UpdateAsync(key,function(old) return stat.Value end)
else
ds:SetAsync(key,stat.Value)
end
end)