To achieve this, you'll need to use Roblox's DataStore system to save and load players' cash. Here's a step-by-step guide on what you need to do:
- In Roblox Studio, insert a script in ServerScriptService.
- Configure the DataStore by adding the following code to the script:
local DataStoreService = game:GetService("DataStoreService")
local cashDataStore = DataStoreService:GetDataStore("CashData")
- Create two functions to save and load player cash:
local function saveCash(player)
local success, errorMessage = pcall(function()
cashDataStore:SetAsync(player.UserId, player.leaderstats.Cash.Value)
end)
if not success then
warn("Error saving cash for Player: " .. player.Name .. ": " .. errorMessage)
end
end
local function loadCash(player)
local cash
local success, errorMessage = pcall(function()
cash = cashDataStore:GetAsync(player.UserId)
end)
if not success then
warn("Error loading cash for Player: " .. player.Name .. ": " .. errorMessage)
return 0
end
if cash then
return cash
else
return 0
end
end
- Create a function to initialize the player when they join the game:
local function onPlayerAdded(player)
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = leaderstats
cash.Value = loadCash(player)
player.CharacterAdded:Connect(function(character)
local billboardGui = Instance.new("BillboardGui")
billboardGui.Parent = character.Head
billboardGui.Size = UDim2.new(10, 0, 1.5, 0)
billboardGui.StudsOffsetWorldSpace = Vector3.new(0, 3.5, 0)
local cashLabel = Instance.new("TextLabel")
cashLabel.Name = "CashLabel"
cashLabel.Parent = billboardGui
cashLabel.Size = UDim2.new(1, 0, 1, 0)
cashLabel.TextXAlignment = Enum.TextXAlignment.Left
cash:GetPropertyChangedSignal("Value"):Connect(function()
cashLabel.Text = "Cash: " .. cash.Value
saveCash(player)
end)
cashLabel.Text = "Cash: " .. cash.Value
end)
end
- Save the player's cash when they leave the game:
local function onPlayerRemoving(player)
saveCash(player)
end
- Connect the functions to the Players service events:
game.Players.PlayerAdded:Connect(onPlayerAdded)
game.Players.PlayerRemoving:Connect(onPlayerRemoving)
Now, when players join your game, their cash amount will be loaded and displayed on the CashLabel in the StarterGUI. The cash value will also be saved when they leave the game. Keep in mind that this is a simple solution, and you should consider handling edge cases and errors that may occur while saving and loading player data.