local Players = game:GetService(“Players”)
local DataStoreService = game:GetService(“DataStoreService”)
local RunService = game:GetService(“RunService”)
local dataStore = DataStoreService:GetDataStore(“Test”) – Always set Datastore to Official when game is ready.
– Function to create leaderstats for a player
local function createLeaderstats(player)
local userID = player.UserId
local key = “Player_”…userID
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
-- Example of a score stat
local clicks = Instance.new("IntValue")
clicks.Name = "Clicks"
clicks.Value = 0
clicks.Parent = leaderstats --NL
local success, returnValue
success, returnValue = pcall(dataStore.GetAsync, dataStore, key)
if success then
if returnValue == nil then
returnValue = {
Clicks = 0, -- NL
}
end
print(returnValue)
clicks.Value = if returnValue.Clicks ~= nil then returnValue.Clicks else 0 --NL
else
player:kick("There was an error loading your data :(. Roblox's Datastore might be down, if not contact out group!")
print(player.Name.."Data loading ERROR!")
end
end
local function save(player)
local userID = player.UserId
local key = “Player_”…userID
local clicks = player.leaderstats.Clicks.Value --NL
local dataTable = {
Clicks = clicks, --NL
}
print(dataTable)
local success, returnValue
success, returnValue = pcall(dataStore.UpdateAsync, dataStore, key, function()
return dataTable
end)
if success then
print("Data Saved!")
else
print("Data Saving ERROR:(")
end
end
local function onShutDown()
if RunService:IsStudio() then
task.wait(2)
else
local finished = Instance.new(“BindableEvent”)
local allPlayers = Players:GetPlayers()
local leftPlayers = #allPlayers
for _, player in ipairs(allPlayers) do
coroutine.wrap(function()
save(player)
leftPlayers -= 1
if leftPlayers == 0 then
finished:Fire()
end
end)()
end
finished.Event:Wait()
end
end
– Connect the createLeaderstats function to the PlayerAdded event
Players.PlayerAdded:Connect(createLeaderstats)
– Iterate through all existing players and create leaderstats for them
for _, player in Players:GetPlayers() do
createLeaderstats(player)
end
Players.PlayerRemoving:Connect(save()
)
game:BindToClose(onShutDown)