Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do you make stats save when you leave the game?

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")

2 comments

0

I am not aware of exactly how to do it, but I am certain that you use DataStoreService for this. For more information on DataStoreService you may go to YouTube and see what is or you can go to the Developer Hub and check some information about it: https://developer.roblox.com/en-us

0

Oh and by the way...game.Players.PlayerAdded is recommended for this event. When wanting to save the data use game.Players.PlayerRemoving so that you can tell the server the user hates the game and leaves it.

2 answers

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)

make sure you test this in game, doesnt work in studio

This discussion is preserved as it was. New answers, comments, and votes are closed.