DataStore2 issue: error when player left! Invalid at input.inventory.1.Target because: Invalid type (Instance)

Today I wanted to do an inventory for my game and I tried implementing the datastore inside the module which is something I’ve never tried before, but I get an error when I leave the game which I have no idea what’s actually causing it

Not sure if it’s for the way I’m implementing it, but by my own logic it looks alright

here’s my code

local serverStorage = game:GetService("ServerStorage")

local DataStore = require(serverStorage.DataStore2)

DataStore.Combine("INVENTORYTEST1", "inventory")

local Inventory = {}
Inventory.__index = Inventory

function Inventory.new(plr: Player)
	local newInventory = {}
	setmetatable(newInventory, Inventory)
	
	local updateEvent = Instance.new("BindableEvent")
	
	--Attributes
	newInventory.Player = plr
	newInventory.DataStore = DataStore("inventory", plr)
	newInventory.Contents = {}
	
	--Events
	newInventory.OnUpdate = updateEvent.Event
	
	local invFolder = Instance.new("Folder")
	invFolder.Parent = plr
	invFolder.Name = "Inventory"
	
	newInventory.DataStore:GetTable({})
	
	newInventory.DataStore:OnUpdate(function(newContents)
		updateEvent:Fire(newContents)
	end)
	
	return newInventory
end

function Inventory:Add(item)
	table.insert(self.Contents, item)
	
	item.Tool:Clone().Parent = self.Player.Backpack
	item.Tool:Clone().Parent = self.Player.StarterGear
	
	self:_GenNewFolder(item)
end

function Inventory:AddAll(content)
	for _, item in pairs(content) do
		self:Add(item)
	end
end

function Inventory:SetAll(content)
	table.clear(self.Contents)
	self:AddAll(content)
end

function Inventory:Save()
	self.DataStore:Set(self.Contents)
end

function Inventory:_GenNewFolder(item)
	local folder = Instance.new("Folder")
	folder.Parent = self.Player.Inventory
	folder.Name = item.Tool.Name
end

return Inventory

In case you wanna see the server script

players.PlayerAdded:Connect(function(plr)
	
	local inventory = Inventory.new(plr)

	local longsword = Longsword.new(serverStorage.Weapons.Swords.Sword, 10, {}, {}, 10)

	inventory:Add(longsword)

	inventory.OnUpdate:Connect(function(newContent)
		inventory:SetAll(newContent)
	end)
	
	players.PlayerRemoving:Connect(function(plr)
		inventory:Save()
	end)
	
end)
1 Like

btw I just realized I shouldn’t set values on playerRemoving so I changed that to set values each change as the documentation says but still have this issue

1 Like

Ok I found the issue

The first one is that I didn’t even put the loaded data in Contents but it didn’t work anyways

The second issue is that the datastore can’t store metatables or instances so to fix this I encoded in JSON format so I can have everything in a string and decoded it when loading

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.