I have been making a saving system that loads all the items you have equipped or that are in the backpack from your last session. When it loads it says that the datastore is nil
Error: https://gyazo.com/9a41cf4de4c9c4f6c6a18bc5ff20cea5
Few disclaimers so that you are able to digest the code.
Function returnBackpack returns the items that is in the players backpack and items that are currently being equipped as a table. Disclaimer: This functions 100% works
local dss = game:GetService('DataStoreService') local datastore = dss:GetDataStore('StoreData') function generateDataKey(player) local ret = "uid_" .. player.UserId return ret end function returnBackpack(plr,val) if val ~= 'removing' then local tbl = {} for i,v in pairs(plr.Backpack:GetChildren()) do table.insert(tbl,v.Name) end for i,v in pairs(plr.Character:GetChildren()) do if v:IsA('Tool') then table.insert(tbl,v.Name) end end return tbl else local tbl = {} for i,v in pairs(plr.Backpack:GetChildren()) do table.insert(tbl,v.Name) end local charTool = game.ReplicatedStorage.changed:InvokeClient(plr) if charTool ~= nil then table.insert(tbl,charTool) end return tbl end end function saveDataForPlayer(player,val) if val ~= 'removing' then local key = generateDataKey(player) local data = returnBackpack(player) local success, err = pcall(function() datastore:SetAsync(key, data) end) else local key = generateDataKey(player) local data = returnBackpack(player,'removing') local success, err = pcall(function() datastore:SetAsync(key, data) end) end end function loadDataForPlayer(player) local char = player.Character or player.CharacterAdded:Wait() local key = generateDataKey(player) local data = datastore:GetAsync(key) for i,v in pairs(data) do local x = game.ServerStorage.Store[v]:Clone() x.Parent = game.Players[player.Name].Backpack end end game.Players.PlayerAdded:Connect(function(player) loadDataForPlayer(player) end) game.Players.PlayerRemoving:Connect(function(player) saveDataForPlayer(player,'removing') end)
Note: This error is not because it is my first time joining the server. I have made sure to test that possibility.
Any help would be appreciated
EDIT: I found the error; when player removing was called, all items in the backpack were removed, and the local script was destroyed, so I had to manually update a table every time a player equipped or unequipped an item to overcome this issue.