Keeps printing something wrong

So, I made a script to check if the player has an item in his backpack and he does have it but it keeps printing that he doesn’t have it. Any answers on why?
Script:

local Prompt = script.Parent.ProximityPrompt
local RandomNumber = math.random(1, 5)

Prompt.Triggered:Connect(function(player)
	for i, v in pairs(player.Backpack:GetChildren()) do
		if v:IsA("Tool") then
			if v.Name == "Lockpick" then
				print("Player has lockpick")
				if RandomNumber == 5 then
					print(RandomNumber)
				end
			else
				print("Player doesn't have lockpick")
			end			
		end
	end
end)

The reason is that it prints if any other tool isn’t a lockpick. Print it after the entire loop of the backpack if you have unsuccessfully not found a lockpick. Just insert return in the place to prevent it from printing:

Prompt.Triggered:Connect(function(player)
	for i, v in pairs(player.Backpack:GetChildren()) do
		if v:IsA("Tool") then
			if v.Name == "Lockpick" then
				print("Player has lockpick")
				if RandomNumber == 5 then
					print(RandomNumber)
				end
				return
			end
		end
	end
	print("Player doesn't have lockpick")
end)
1 Like

This code is correct, but if a player is holding/equips the tool it will no longer show in the player.Backpack.
The tool gets moved to the player.Character so you need to check there as well.

Here is the extra code to do so.

for i, v in pairs(player.Backpack:GetChildren()) do
	if v:IsA("Tool") then
		if v.Name == "Minecraft Diamond Sword in backpack" then
			print("Player has lockpick")
		end			
	end
end
for i, v in pairs(player.Character:GetChildren()) do
	if v:IsA("Tool") then
		if v.Name == "Minecraft Diamond Sword" then
			print("Player has lockpick in character")
		end			
	end
end
2 Likes

Thought of that but I am just testing it while it’s not being equipped but will definitely add that if I want it with equipped, Thank you

people already solved this problem, but here is the actual solution which should work if they also have it equipped

local Prompt = script.Parent.ProximityPrompt
local RandomNumber = math.random(1, 5)

Prompt.Triggered:Connect(function(player)
	if (player.Backpack:FindFirstChild("Lockpick")) or (player.Character and player.Character:FindFirstChild("Lockpick")) then
		print("Player has lockpick")
		if RandomNumber == 5 then
			print(RandomNumber)
		end
	else
		print("Player does not have lockpick")
	end
end)

no need to loop through the children, a function like this already exists

2 Likes

I tried using it, it just keeps on printing player does not have lockpick when I have it

player.Backpack.ChildAdded:Connect(function()
   if player.Backpack:FindFirstChild("Lockpick") then
      print("Lockpick found!")
   else
      print("Lockpick couldn't be found!")
   end
end)

You can try something like this. Of course, if they have it equipped then you would check the character instead.