Detecting If A Tool Is Interacting With An Object

Heya people, i’m Joni_R2D and my game mainly focuses on tools, so i want the tool to interact with other objects and such, for an example: If a player uses the tool on a button, then an object breaks. But the problem is that i don’t know how to detect if something is being interacted/touched by a tool or a player.

3 Likes

???

Please give us some code at least , and tell us what that button is
is it… a gui button?
or a click detector that you are referring to as a button

You can detect when a tool is used by creating a LocalScript parented to the tool directly,

local tool = script.Parent
 tool.Activated:Connect(function()
  local char = tool.Parent
 local humanoid = char:FindFirstChild("Humanoid")
 --do something

print ( char.Parent.Name .. "has activated the tool")
end
end)

Well you want to create an tool which destroys an object on touched. This can esaily be done like this:

script.Parent.Touched:Connect(function(hit)
     if hit.Parent:FindFirstChild("Humanoid") == nil then -- we make sure it's not a player tocuhed
         hit.Parent:Destroy()
     end 
end)

This should be put inside your tool.

Okay, going to try that right now.

1 Like

You probablly already have a Touched funciton in your tool thought so be careful about that.

It didn’t work, can you tell me what is wrong?

image

The tool’s script has the code that you sent me.

Here is a code for your tool:

script.Parent:FindFirstChild("Handle").Touched:Connect(function(hit)
     if hit:FindFirstChild("Humanoid") == nil then -- we make sure it's not a player tocuhed
       if  hit ~= nil then
         hit:Destroy()
         end
     end 
end)
3 Likes

Thank you! It looks like it’s fully working now, :slight_smile:

1 Like

Another method here, you can detect a nearby part by using rays which go in the Handle’s lookVector.
If it detects one then run the necessary checks and :Destroy it.
I’m Binding this to RenderStep for faster detection:

local handle = script.Parent

game:GetService("RunService"):BindToRenderStep("toolRaycast", Enum.RenderPriority.Camera + 1, function()
    local ray = Ray.new(handle.Position, handle.CFrame.LookVector * 2) --2 is how many studs close
    local part = ray:FindPartOnRay(ray, handle)

    if not part.Parent:FindFirstChild("Humanoid") then
        part:Destroy()
    end
end)
2 Likes

It seems like everything is worked out, however one resource I’d really recommend is this:

Touched isn’t all that great so I felt like I should add my two cents.

While you may need some animations (for improved accuracy, I think), it’s really a great idea for future reference.