How can i modify this script so it saves when i leave the game?
function newPlayer(player) local stats = Instance.new("Folder",player) stats.Name = "leaderstats" local points = Instance.new("IntValue") points.Name = "Points" points.Value = 0 local survivals = Instance.new("IntValue") survivals.Name = "Survivals" survivals.Value = 0 points.Parent = stats survivals.Parent = stats stats.Parent = player end game.Players.ChildAdded:connect(newPlayer) bin.running.Changed:connect(function () runningChanged(bin.running) end) print("Leaderboard Loaded")
Add these as variables
local DSS = game:GetService(“DataStoreService”) local DS = DSS:GetDataStore(“DataStore”)
Put this inside of the newPlayer
function
after line 15
local Data local s,e pcall(function() Data = DS:GetAsync(“UserId:”.. Player.UserId) end) if s then points.Value = Data[1] survivals.Value = Data[2] print(“Data loaded”) end
Put this inside a new function that will be named saveData()
local function saveData(Player) local Data = {} table.insert(Data,1,Player.leaderstats.Points.Value) table.insert(Data,2,Player.leaderstats.Survivals.Value) -- Way better ways to do this part lol local s,e = pcall(function() DS:SetAsync(“UserId:”.. Player.UserId,Data) end) end
and just add this at line 19
game.Players.PlayerRemoving:Connect(saveData)