Check if player has item inside Inventory folder

Ok so I made a shop script and you can only have a maximum of one tool in your inventory.

So I tried to check if the player had the same tool in their inventory folder (not backpack) by doing using Player:FindFirstChild(“Inventory”):FindFirstChild(“Bear Trap”). It doesn’t work and instead stays stuck at that line for some reason and doesn’t let anything else run inside the while loop

-- Checks if you already have bear trap, then it automatically disables buying
local notallowed = true
while wait(0.2) do
	if Player:FindFirstChild("Inventory"):FindFirstChild("Bear Trap") then
		notallowed = true
	else
		notallowed = false
	end
	if Player:FindFirstChild("ToolSave")["Bear Trap"].Value == true and notallowed == true then
		for i,v in pairs(Button:GetChildren()) do
			if v:IsA("UIGradient") then
				v:Destroy()
			end
		end
		local Unavaliable = Gradients.Unavaliable:Clone()
		Unavaliable.Parent = Button
		Button.Text = "MAX: 1"
	end
	if Player:FindFirstChild("ToolSave")["Bear Trap"].Value == false or notallowed == false then
		for i,v in pairs(Button:GetChildren()) do
			if v:IsA("UIGradient") then
				v:Destroy()
			end
		end
		local Avaliable = Gradients.Avaliable:Clone()
		Avaliable.Parent = Button
		Button.Text = Cost.." BOLTS"
	end
end

If “Inventory” doesn’t exist, it’ll return nil. Since you have two findfirstchilds back-to-back, what actually ends up running when inventory doesn’t exist is:

nil:FindFirstChild("Bear Trap")

which would error because nil doesn’t exist, and it’s trying to index this non-existent value with FindFirstChild.
Fix:

if Player:FindFirstChild("Inventory") and Player.Inventory:FindFirstChild("Bear Trap") then

end
2 Likes

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