Function is running multiple times after being called once

basically im trying to make a script for chopping trees using a tool and its working really well other than the fact that it keeps firing a bunch after the tool is first activated (code is originally from this post)

local Tool = script.Parent
local Handle = Tool.Handle
--local Animation = Tool.Animation
debounce = false
local damage = 1

function checkTree()
	Handle.Touched:Connect(function(hit)
		local t = hit.Parent:FindFirstChild("wood")
	if t then
		if not debounce then
			debounce = true
			print("Tree Detected")
			local hits = hit.Hits

			hits.Value += 1

			wait(1)
			debounce = false
		else
			print("No Tree")
			wait(1)
		end
	end
	end)
end

Tool.Activated:Connect(function()
	print("checking tree")
	checkTree()
	
end)

image
(output) The “checking tree” fires perfectly but tree detected and no tree fire continuously after i first click with the tool

1 Like

why cant luau just act like python for once

Because you are connecting a function to an event and not doing it once the tool is deactivated and as such, the function continues to run every time the event fires. You can ofc dc the event in tool.Deactivated but a better method would be:

function checkTree()
	for _, touchingPart in Handle:GetTouchingParts() do
        local t = hit.Parent:FindFirstChild("wood")

		if t then
			if not debounce then
				debounce = true
				print("Tree Detected")
				local hits = hit.Hits
		
				hits.Value += 1
		
				wait(1)
				debounce = false
			else
				print("No Tree")
				wait(1)
			end
		end
	end
end
2 Likes