This function fires whenever a player collects an item
ItemCollected.OnServerEvent:Connect(function(player, item)
local User = PlayerData[player.UserId]
if not User then return end
-- Check if the table is already in their backpack
for i, v in pairs(User.Backpack) do
if i == item then
v = v + 1
DataUpdated:FireClient(player, User)
return
end
end
-- New item, so need to create new table
local NewItem = {item = 1}
table.insert(User.Backpack, NewItem)
DataUpdated:FireClient(player, User)
end)
Now, by default the players backpack is
User.Backpack = {}
And how it my function works is it checks your backpack to see if you already have that item there, if not then it creates a new item and sets its value to 1, so if you collect a piece of wood it should look like this:
User.Backpack = {
Wood = 1
}
Collect steel, it’ll check, see that steel isn’t in your backpack, so create steel
User.Backpack = {
Wood = 1,
Steel = 1
}
Now if you collect another piece of wood, it should see that you already have wood created in your backpack, so instead of going
User.Backpack = {
Wood = 1,
Steel = 1,
Wood = 1
}
It should go
User.Backpack = {
Wood = 2,
Steel = 1
I’m not getting any errors however I don’t believe it’s not adding new items properly, as if I go
for i, v in pairs(User.Backpack) do
print(i, v)
end
It should print Wood 2, Steel 1, but instead prints 1 table