This datastore won’t save for some reason. It has no problem loading, but when you leave the game, this error occurs:
Workspace.Script:32: attempt to index nil with 'UserId' - Server - Script:39
Here is the script:
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local level = Instance.new("IntValue")
level.Name = "Level"
level.Parent = leaderstats
local data = print("Successfully loaded data!")
local success, errormessage = pcall(function()
myDataStore:GetAsync(player.UserId.."-level")
end)
if success then
level.Value = data
else
print("There was an error when attempting to load your data")
warn(errormessage)
end
while true do
wait(5)
level.Value = level.Value + 1
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function(player)
myDataStore:SetAsync(player.UserId.."-level",player.leaderstats.Level.Value) -- This is the line that's erroring.
end)
if success then
print("Player Data has been saved!")
else
print("There was an error while trying to save data.")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId.."-level",player.leaderstats.Level.Value) -- This is the line that's erroring.
end)
if success then
print("Player Data has been saved!")
else
print("There was an error while trying to save data.")
warn(errormessage)
end
end)
local myDataStore = game:GetService("DataStoreService"):GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local level = Instance.new("IntValue")
level.Name = "Level"
level.Parent = leaderstats
local data = nil
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(player.UserId.."-level")
end)
if success then
level.Value = (data or 0)
else
warn("There was an error when attempting to load your data.\n"..errormessage)
end
while wait(5) do
level.Value += 1
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId.."-level", player.leaderstats.Level.Value)
end)
if success then
print("Player Data has been saved!")
else
warn("There was an error while trying to save data.\n"..errormessage)
end
end)