Roblox Data Storage - Full Script

in #roblox6 years ago (edited)

A video tutorial will be added later


-- Setting up the DataStorage
local Players = game:GetService("Players")
local cashStorage = game:GetService("DataStoreService"):GetDataStore("Cash")

-- Defining the joining player function
local function onPlayerAdded(player)

-- "player-" may be changed to anything else, it's just a an identifier
playerKey = "player-" .. player.UserId

-- Setting up the leaderboard/leaderstats
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player

-- Creating the "Cash" value
local cash = Instance.new("IntValue", leaderstats)
cash.Name = "Cash"

-- Checking if joined player already has saved data, retrieving it, if yes
local myCash
local success, err = pcall(function()
myCash = cashStorage:GetAsync(playerKey)
end)
if success then
cash.Value = myCash
else
cash.Value = 10000 --Setting the default Cash value to 10000
end
end

local function onPlayerLeaving(player)
cashStorage:setAsync(playerKey, 100)
end

-- Loading the saved data on player join // Saving the player data on player leaving
Players.PlayerAdded:Connect(onPlayerAdded)

Players.PlayerRemoving:Connect(
function(player) -- Function that saves the data on leaving
cashStorage:setAsync(playerKey, player.leaderstats.Cash.Value) --
end)

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.029
BTC 76530.78
ETH 3054.36
USDT 1.00
SBD 2.63