Hello, I am trying to make saving stages for my obby. But I have spent hours on it and it hasn’t worked… (sorry for bad explanation, I haven’t for a bit so I’m kinda dizzy.)
Here is my script:
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local database = dataStoreService:GetDataStore("Stages")
local sessionData = {}
function PlayerAdded(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
local stage = Instance.new("IntValue")
stage.Parent = leaderstats
stage.Name = "Stage"
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 database")
if not playerData then
print("Assigning default data")
playerData = {
["Stage"] = 1
}
end
sessionData[player.UserId] = playerData
else
warn("Unable to get data for", player.UserId)
player:Kick("Unable to load your data! Please try again later.")
end
stage.Value = sessionData[player.UserId].Stage
stage.Changed:Connect(function()
sessionData[player.UserId].Stage = stage.Value
end)
leaderstats.Parent = player
end
players.PlayerAdded:Connect(PlayerAdded)
function PlayerLeaving(player)
if sessionData[player.UserId] then
print("test")
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)