Hi,
I am trying to find if a player has a tool when they touch a hitbox in a server script but can’t get it to work, below is what I have so far but errors with cant find Backpack, I think it may be because I need to check the character but not sure how to do this?
script.Parent.HitBox1.Touched:Connect(function(hit)
local ToolName = "TestTool1"
local Player = hit.Parent
-- Error Backpack is not a valid member of Model "Workspace.CanterCrow"
if Player.Backpack:FindFirstChild(ToolName) then
print("Player has tool in backpack!")
else
print("Player does not have tool in backpack!")
end
1 Like
I figured it out,
local Players = game:GetService("Players")
local TouchPart = script.Parent
local Tool = "TestTool"
TouchPart.Touched:Connect(function(touched)
if touched.Parent:IsA("Model") and touched.Parent:FindFirstChild("Humanoid") then
local Player = Players:GetPlayerFromCharacter(touched.Parent)
if Player.Character:FindFirstChild(Tool) or Player.Backpack:FindFirstChild(Tool) then
print("Key card found")
end
end
end)
1 Like
The issue is that you mistake the player with the player character, also hit.Parent
may not even be the player character but a random part. Here’s a simple function that takes the player character and the tool name as input and returns true or false depending on if the player has the tool:
--Why this? Just in case the character has a part with the same name as the tool
function GetByClassAndName(parent: Instance, class: string, name: string): Instance?
for _, child in pairs(parent:GetChildren()) do
if child:IsA(class) and child.Name == name then return child end
end
return nil
end
function HasTool(char: Model, name: string): boolean
--if it's equipped
if GetByClassAndName(char, "Tool", name) then return true end
--if it's not equipped
local player = game.Players:GetPlayerFromCharacter(char)
if not player then
warn("Player doesn't exist for "..char.Name)
return false
end
return (GetByClassAndName(player.Backpack, "Tool", name) ~= nil)
end
script.Parent.Touched:Connect(function(hit)
if not hit.Parent:IsA("Model") then return end
if not hit.Parent:FindFirstChildWhichIsA("Humanoid") then return end
--you can comment the player check if you want it to work for NPC's with the tool in their model too
if not game.Players:GetPlayerFromCharacter(hit.Parent) then return end
if HasTool(hit.Parent, "TestTool") then
print("Key card found")
end
end)
Also if the post is solved mark the reply that solved it as a solution.
1 Like