-- Services
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")
local RS = game:GetService("RunService")
local Data = DSS:GetDataStore("Data")
local currentSession = {}
-- Variables
function player_added(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
local Punches = Instance.new("IntValue")
Punches.Name = "Punches"
Punches.Value = 0
Punches.Parent = leaderstats
local Wins = Instance.new("IntValue")
Wins.Name = "Wins"
Wins.Value = 0
Wins.Parent = leaderstats
local success = nil
local playerData = nil
local attempt = 0
repeat
success,playerData = pcall(function()
return Data:GetAsync(player.UserId)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(3)
end
until success or attempt >= 4
if success then
print("Database has been initialized")
if not playerData then
print("Player data doesn't exist, assigning default value.")
playerData = {
["Punches"] = 0,
["Wins"] = 0,
}
end
currentSession[player.UserId] = playerData
else
warn("Unable to access Database")
player:Kick("We are unable to load your data. Please contant a developer or try again later.")
end
Punches.Value = currentSession[player.UserId].Punches
Wins.Value = currentSession[player.UserId].Wins
Punches.Changed:Connect(function()
currentSession[player.UserId].Punches = Punches.Value
end)
Wins.Changed:Connect(function()
currentSession[player.UserId].Wins = Wins.Value
end)
leaderstats.Parent = player
end
function player_leave(player)
if currentSession[player.UserId] then
local success = nil
local errorMSG = nil
local attempt = 0
repeat
success,errorMSG = pcall(function()
Data:SetAsync(player.UserId, currentSession[player.UserId])
end)
attempt += 1
if not success then
warn(errorMSG)
task.wait(3)
end
until success or attempt >= 4
if success then
print("Data for : " .. player.UserId .. " has been saved.")
else
warn("Unable to save data for : " .. player.UserId .. " please contact a developer.")
end
else
warn("Unable to save data due to player being Nil.")
end
end
function server_shutdown()
for i, player in ipairs(Players:GetPlayers()) do
task.spawn(function()
player_leave()
end)
end
end
game:BindToClose(server_shutdown)
Players.PlayerAdded:Connect(player_added)
Players.PlayerRemoving:Connect(player_leave)
ServerScriptService.Data.DataSavingLeaderStats:72: attempt to index nil with ‘UserId’
This works on my other game but not this one. Can anyone help me? Thank you