Roblox Data Storage - Full Script

in roblox •  6 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)

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!