I wanted to make a brick that removes current tool that player is holding. I made this script:
function onTouched(hit) if hit.Parent:findFirstChild("Tool").Name == "Gun" then local gun = hit.Parent.findFirstChild("Tool").Name gun:Destroy() end end script.Parent.Touched:connect(onTouched)
And it doesn't work! Can someone help me?
You're not destroying the tool instance! When you defined 'gun' on line 3
, you indexed the Name Property. By doing this, 'gun' is a string, corresponding to the name of the first found child in the directory of your Backpack, named "Tool". So, if such tool was ever found then 'gun' is ALWAYS only ever going to be a string, "Tool".
1)
Rather than using the FindFirstChild
function in a conditional, you should iterate through the Character's descendants. This is necessary due to the fact that any equipped tool is Parented into the Character.
2)
Don't check for the name of the tool, since if you make other tools and want to name them other things then they would not pass the conditional. Check for the Class. You can either use the IsA
function or the ClassName
property to determine whether or not the current iteration is a tool.
3)
Define 'gun' as the actual tool! Not the Name Property of the tool!
function onTouched(hit) --Check for a humanoid if hit.Parent:FindFirstChild("Humanoid") then --Iterate through the character for _,v in next, hit.Parent do --Check if current iteration is a tool if v:IsA("Tool") or v:IsA("HopperBin") then --Destroy the tool v:Destroy() end end end end script.Parent.Touched:connect(onTouched)