Touched event working fine, then not?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to fix a bug, in which when axe collides with tree (axe activated), it’s hp decreases.

  2. What is the issue? Include screenshots / videos if possible!
    At first collision, everything works fine, but after that the tree’s hp decreases when axe is activated even if not colliding with the tree. video:

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I looked for solutions for a few days, tried to add debounces, other changes in code, but none of them worked.

Tree Script:

local canTouch = true
local partHealth = 20
local debounce = true
local tree = script.Parent
script.Parent.BillboardGui.hp.Text = "20"

tree.Touched:Connect(function(hit)
	if hit.Parent.Name == "BasicAxe" then
		if hit.Parent.Activated:Connect(chopDownBasicAxe) then

		end
	end
end)

function chopDownBasicAxe()
	if debounce == true then
		debounce = false
	partHealth = partHealth - 1

	script.Parent.BillboardGui.hp.Text = partHealth

	if partHealth < 1 then
		tree.Transparency = 1
			tree.Position = Vector3.new(0,1000,0)
			
			game.ReplicatedStorage.Reward.OnServerEvent:Connect(function(player)
				player.leaderstats.Cash.Value = player.leaderstats.Cash.Value + 10
			end)
			
		wait(math.random(3,8))
		partHealth = 20
		script.Parent.BillboardGui.hp.Text = partHealth
		tree.Position = Vector3.new(math.random(-20, 50), 8, math.random(-44, 15))
			tree.Transparency = 0
		end
		wait(1.5)
		debounce = true
	end
end

the event would never be removed
until the code that runs the event is removed which is also a event that is the touched event
also since the event is not getting removed it will multiply infinity

instead you could call or run it once
by either disconnecting the event using ** Disconnect () ** once the function is finished or call the event using Wait () it will just wait for the event and run the next code once

try this on the touch event line

tree.Touched:Connect(function(hit)
	if hit.Parent.Name == "BasicAxe" then
		hit.Parent.Activated:Wait()
		chopDownBasicAxe()
	end
end)
2 Likes

i tried it, now it works perfectly. thanks man, appreciate it!