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

Database/saving stuff help?

How do I save things like for example a player's personal variable titled money or the amount of kills they have to the database so when they join a different server that is still my game all their stats are transferred. It doesn't matter what it saves all I need is an example or some wiki links on how to do this

1 answer

First off you need a leaderboard:

game.Players.PlayerAdded:connect(function(plr)
	local stats = Instance.new("IntValue", plr)
	stats.Name = "leaderstats" 
	
	local money = Instance.new("IntValue", stats)
	money.Name = "Money" -- Name of your stats
end)

After that you will need to get the DataStoreService:

local Data = game:GetService("DataStoreService"):GetDataStore("NameOfDS")

You will need to get the players key to do this you create a new local variable inside of the leaderboard. You will create another variable called saved:

local key = "plr-"..plr.userid
local saved = Data:GetAsync(key)

You need an if statement to check if saved == nil. If its not == nil then we have to load the data from before:

if Saved then
		money.Value = saved[1]
	else
		local ValuesToSave = {money.Value }
		Data:SetAsync(key, ValuesToSave)
	end

After you do that you need to create a event that saves the values when the player leaves the game:

game.Players.PlayerRemoving:connect(function(plr)
	local money = game.Players.LocalPlayer.leaderstats.Money
	local key = "plr-"..plr.userid
	local valuesToSave = {money.Value}
	
	Data:SetAsync(key, valuesToSave)
end)

final script:

local Data = game:GetService("DataStoreService"):GetDataStore("NameOfDS")

game.Players.PlayerAdded:connect(function(plr)
	local stats = Instance.new("IntValue", plr)
	stats.Name = "leaderstats" 
	
	local money = Instance.new("IntValue", stats)
	money.Name = "Money" -- Name of your stats

	local key = "plr-"..plr.userid
	local saved = Data:GetAsync(key)
		if Saved then
				money.Value = saved[1]
			else
				local ValuesToSave = {money.Value }
				Data:SetAsync(key, ValuesToSave)
		end
end)

game.Players.PlayerRemoving:connect(function(plr)
	local money = game.Players.LocalPlayer.leaderstats.Money
	local key = "plr-"..plr.userid
	local valuesToSave = {money.Value}
	
	Data:SetAsync(key, valuesToSave)
end)

This is just a basic version of data store but hope this helps. You can do a lot more with Data Store when you learn more about it. Just realized you posted this 3 years ago. LOL

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