I have this datastore that saves both inventory AND numbers, here it is (serverscript in serverscriptservice)
local datastore = game:GetService("DataStoreService"):GetDataStore("BronzeDarkRPstats")
local dataTable = {}
function save(plr)
dataTable.cash = plr.Cash.Value
dataTable.karma = plr.Karma.Value
dataTable.inventory = {}
for _,item in ipairs(plr:WaitForChild("Inventory"):GetChildren()) do
table.insert(dataTable.inventory,item.Name)
print("saved "..item.Name.." into datastore")
end
local success,failure = pcall(function()
datastore:UpdateAsync(plr.UserId,function(data)
local currentData = data
return currentData
end)
end)
if success then
print('data saved')
elseif failure and not success then
print(failure)
warn('data failed to save')
end
for i,v in pairs(workspace:GetDescendants()) do
if v.Name == plr.Name.."_Item" then
v:Destroy()
end
end
end
function load(plr)
local data
local success,failure = pcall(function()
data = datastore:GetAsync(plr.UserId) --load
end)
if success and data then
plr.Cash.Value = data.cash
plr.Karma.Value = data.karma
for i,v in ipairs(data.inventory) do
local item = game.ReplicatedStorage.Items:FindFirstChild(v)
if item then
local clone = item:Clone()
clone.Parent = plr.Inventory
print('loaded '..item.Name)
end
end
print("successfully loaded data")
elseif failure and not success then
print(failure)
warn('data did not load')
end
end
game:GetService("Players").PlayerAdded:Connect(function(plr)
local Cash = Instance.new("IntValue")
Cash.Parent = plr
Cash.Name = 'Cash'
Cash.Value = 10000
local Karma = Instance.new("IntValue")
Karma.Parent = plr
Karma.Name = 'Karma'
load(plr)
end)
game.Players.PlayerRemoving:Connect(function(plr)
save(plr)
end)
game:BindToClose(function()
for _, Player in ipairs(game.Players:GetPlayers()) do
coroutine.wrap(save, Player);
end
end)
To help you understand, let's say the player has 7 apples in their inventory. The server removes 5 of them, leaving 2 apples left. When the player leaves, it prints that it saved 2 apples in their inventory. However when they join back, it loads 7 apples...
I'm still very new to datastores and not experienced with them. It confuses me very often and I have no idea why this isn't working as intended...
Any help is greatly appreciated!
