When you read and overwrite data your not typing the correct function names.
Reading data
To read data you need to use GetAsync() not GetSync()
Example:
local data = game:GetService("DataStoreService"):GetDataStore("Inventory")
game.Players.PlayerAdded:Connect(function(plr)
local SavedItems = data:GetAsync(plr.UserId)
end
Saving data
This is the same problem as reading data. You named the functions incorrectly.
Sync() is not a function of DataStore. Instead of using Sync() use SetAsync() which will overwrite data.
Example:
game.Players.PlayerRemoving:Connect(function(plr)
local Table = {}
for i, v in pairs(plr.Backpack:GetChildren()) do
table.insert(Table,v.Name)
end
if Table ~= nil then
data:SetAsync(plr.userId,Table)
end
end)
Here is a re-written version of your script:
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("Inventory")
local function Load(plr)
local key = "plr-"..plr.UserId
local savedData
local success, err = pcall(function()
savedData = DataStore:GetAsync(key)
end
if not success then
warn("Failed to read data"..tostring(err))
return
end
if savedData then
for i, v in pairs(savedData) do
if v then
local item = game.ServerStorage.Inventory:FindFirstChild(v):Clone()
if item then
item.Parent = plr:WaitForChild("Backpack")
end
end
end
else
local items = {}
local itemsSaving = plr:WaitForChild("Backpack"):GetChildren()
for i, v in pairs(itemsSaving) do
if v then
table.insert(items, v.Name)
end
end
local success, err = pcall(function()
DataStore:SetAsync(key, items)
end
if not success then
warn("Failed to overwrite data"..tostring(err))
return
end
end
end
local function SaveData(plr)
local key = "plr-"..plr.UserId
local items = {}
local itemsSaving = plr:WaitForChild("Backpack"):GetChildren()
for i, v in pairs(itemsSaving) do
if v then
table.insert(items, v.Name)
end
end
local success, err = pcall(function()
DataStore:SetAsync(key, items)
end
if not success then
warn("Failed to overwrite data"..tostring(err))
return
end
end
game.Players.PlayerAdded:Connect(Load)
game.Players.PlayerRemoving:Connect(SaveData)
Now you might not need to use the pcalls but they sure came in handy to me. NOTE: "THIS SCRIPT IS NOT TESTED. IT COULD THROW ERRORS AND MAY NOT WORK."
(Used caps lock not to be mean but to make sure you see that)
I wrote the script above to fix any bugs with your script. It should work just by copying the script but you may have some tweaking to do. Hope this helps!
6 comments
code blocks plz
code blocks pls
Looks ok to me but hard to read without codeblocks...but you also need an Inventory folder in ServerStorage and the tool to save in that folder, if you add the item to workspace and collect it, it should then work
Thats the way your script is setup
so i should put a folder in serverstorage with the item inside?
Yes, make sure the folder is named “Inventory”, have a clone of the item in workspace for the initial collection by the player