Im trying to make a datastore script but it wont save, it gives me the error message "attempt to index nil with UserId". I dont know how to fix it. Here is my code:
local datastoreservice = game:GetService("DataStoreService")
local datastorage = datastoreservice:GetDataStore("datastorage")
print("Variables loaded")
local function Load(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Nights = Instance.new("IntValue")
Nights.Name = "Nights"
Nights.Parent = leaderstats
print("Leaderstats created")
local data
local success, errormessage = pcall(function()
data = datastorage:GetAsync(player.UserId)
end)
print("Data load happened")
if success then
print("Data loaded")
else
warn("Error happened while loading data: "..errormessage)
end
end
local function Save(player)
local success, errormessage = pcall(function()
datastorage:SetAsync(player.UserId, player.leaderstats.nights.Value)
end)
if success then
print("Data saved")
else
warn("Error happened while saving data: "..errormessage)
end
end
game.Players.PlayerAdded:Connect(Load)
game:BindToClose(Save)
Please help me, ive been having issues with datastoring for a few days

1 comment
Thank you