-- Script --
--// Services
local Players = game:GetService("Players") -- Access the Players service
local DataStoreService = game:GetService("DataStoreService") -- Access the DataStore service
--// DataStore
local coinDataStore = DataStoreService:GetDataStore("leaderstats") -- Create or access a DataStore named "leaderstats"
--// Function to create leaderstats for a player
local function createLeaderstats(player)
-- Create a folder named "leaderstats" (required for Roblox leaderboards)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
-- Create an IntValue to store the player's coins
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
-- Try to load the player's saved coin data
local success, savedCoins = pcall(function()
return coinDataStore:GetAsync(player.UserId) -- Use UserId as a unique key
end)
-- If data was successfully loaded, set the coin value
if success and savedCoins ~= nil then
coins.Value = savedCoins
else
-- If no data was found or there was an error, start with 0 coins
coins.Value = 0
end
end
--// Function to save player data when they leave
local function savePlayerData(player)
-- Find the Coins value inside the player's leaderstats
local coins = player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Coins")
if coins then
-- Try to save the coin value to the DataStore
local success, errorMessage = pcall(function()
coinDataStore:SetAsync(player.UserId, coins.Value)
end)
-- Optional: print error if saving fails
if not success then
warn("Failed to save coins for " .. player.Name .. ": " .. errorMessage)
end
end
end
--// Connect player events
Players.PlayerAdded:Connect(createLeaderstats) -- When a player joins, create their leaderstats
Players.PlayerRemoving:Connect(savePlayerData) -- When a player leaves, save their data