What are you attempting to achieve? im trying to save data when player is leaving
What is the issue? attempt to index “nil” with “UserId”
What solutions have you tried so far? nothing, i dont know how to modify this script and yes, i searched on roblox wiki, forums Youtube and discord, still nothing
local plrs = game:GetService("Players")
local dataServ = game:GetService("DataStoreService")
local sessionData = {}
local Database = dataServ:GetDataStore("HealthData")
function PlayerAdded(player)
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 for ")
if not playerData then
print("assigned default data")
playerData = {
["MaxHealth"] = 20,
["WalkSpeed"] = 16
}
end
sessionData[player.UserId] = playerData
else
warn("Unable to get data")
player:Kick("Unable to find your data, please try again later")
end
player.Character.Humanoid.MaxHealth = sessionData[player.UserId].MaxHealth
player.Character.Humanoid.Changed:Connect(function()
sessionData[player.UserId].MaxHealth = player.Character.Humanoid.MaxHealth
end)
end
plrs.PlayerAdded:Connect(PlayerAdded)
function PlayerLeaving(player)
if sessionData[player.UserId] then --getting error message here
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
print("Unable to save", player.Name )
end
end
end
plrs.PlayerRemoving:Connect(PlayerLeaving())
This. You need to remove the empty () that appear after the function name. This is because if you don’t remove them, instead of connecting the event to that function, you’re trying to connect the event to the result of that function, which errors because it doesn’t have a Player passed in.