Hello!
I’m currently trying to make a leaderstats system that saves whenever the player leaves and joins back using DataStores, but can’t seem to make this script I followed on a tutorial work.
Help is much appreciated.
local Players = game:GetService("Players")
local leaderstats = Instance.new("Folder")
local RunService = game:GetService("RunService")
local DataStoreService = game:GetService("DataStoreService")
local database = DataStoreService:GetDataStore("data")
local sessionData = {}
leaderstats.Name = "leaderstats"
function PlayingAdded(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local points = Instance.new("IntValue")
points.Name = "BitCoin"
points.Value = 0
local success = nil
local playerData = nil
local attempt = 1
repeat
success, playerData = pcall(function()
return database:GetAsync(player.UserId)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(3)
end
until success or attempt == 5
if success then
print("Connected to date base")
if not playerData then
print("Assigning default data")
playerData = {
["points"] = 0,
}
end
sessionData[player.UserId] = playerData
else
warn("Unable to get data for", player.UserId)
player:Kick("We were Unable to load your data. You wouldn't want to start over would you? Didn't think so... Just go ahead and try again later")
end
points.Value = sessionData[player.UserId].points
points.Changed:Connect(function()
sessionData[player.UserId].points = points.Value
end)
points.Parent = leaderstats
end
Players.PlayerAdded:Connect(PlayingAdded)
function PlayerLeaving(player)
if sessionData[player.UserId] then
local success = nil
local errorMsg = nil
local attempt = 1
repeat
success, errorMsg = pcall(function()
database:SetAsync(player.UserId, sessionData[player.UserId])
end)
attempt += 1
if not success then
warn(errorMsg)
task.wait(3)
end
until success or attempt == 5
if success then
print("Data saved for", player.Name)
else
warn("Unable to save for", player.Name)
end
end
end
Players.PlayerRemoving:Connect(PlayerLeaving)
function ServerShutdown()
if RunService:IsStudio() then
return
end
print("Server shutting down...")
for i, player in ipairs(Players:GetPlayers()) do
task.spawn(function()
PlayerLeaving(player)
end)
end
end
game:BindToClose(ServerShutdown)