I need to save the cookbooks that the player has bought in my game. When they collect a cookbook, it is a bool value added into the CookbooksCollected folder in the player, that works fine.
Loading the data works successfully, so I haven’t included that part of the script, but for some reason saving doesn’t work. It saved once, but never worked again, I didn’t make any changes either. There is an error message: “ServerScriptService.SavingCollectedBooks:73: attempt to index nil with 'CookbooksCollected”. I don’t really know what’s wrong with it, so I would really appreciate some help!
local DataStoreService = game:GetService("DataStoreService")
local collectedDataStore = DataStoreService:GetDataStore("collectedCookbooks")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CookbookList = ReplicatedStorage:WaitForChild("Cookbooks")
game.Players.PlayerRemoving:Connect(function(Player)
--saving collected cookbooks
local success, errormessage = pcall(function()
local CollectedSave = {}
for i, cookbook in pairs(Player.CookbooksCollected:GetChildren()) do
if cookbook then
table.insert(CollectedSave, cookbook.Name)
end
end
collectedDataStore:SetAsync("User-"..Player.UserId, CollectedSave)
end)
if success then
print("Data has been saved.")
else
print("Data has NOT been saved.")
warn(errormessage)
end
end)
game:BindToClose(function(Player)
--saving collected cookbooks
local success, errormessage = pcall(function()
local CollectedSave = {}
for i, cookbook in pairs(Player.CookbooksCollected:GetChildren()) do -- this is where the error message is.
if cookbook then
table.insert(CollectedSave, cookbook.Name)
end
end
collectedDataStore:SetAsync("User-"..Player.UserId, CollectedSave)
end)
if success then
print("Data has been saved.")
else
print("Data has NOT been saved.")
warn(errormessage)
end
end)
Thank you so much!