Why does the event fire many times?

I made a hitbox function when it touches a humanoid it fires an event, but for some reason it fires many times.

Script 1:

	local hitboxsize = Vector3.new(15,10,10)
	local hitbox = Instance.new("Part")
	hitbox.Size = hitboxsize
	hitbox.Parent = workspace
	hitbox.Anchored = true
	hitbox.CanCollide = false
	hitbox.CFrame = flame1.CFrame * CFrame.new(7.5,0,0)
	
	hitbox.Touched:Connect(function(hit)
		local dmgamount = 7.5
		local hitboxevent = game.ReplicatedStorage.Events.HitBoxEvent
		local character = hit.Parent
		local hithumanoid = character:FindFirstChild("Humanoid")
		if hithumanoid then
			hitboxevent:Fire(dmgamount, hithumanoid)
			else
		end
	end)
	wait()
	hitbox:Destroy()

script 2:

local hitboxevent = game.ReplicatedStorage.Events.HitBoxEvent

hitboxevent.Event:Connect(function(dmgamount, hithumanoid)
	print(dmgamount)
	hithumanoid:TakeDamage(dmgamount)
	hithumanoid.WalkSpeed = 0
	hithumanoid.JumpHeight = 0
end)
1 Like

This is because you don’t Have any Debounces . As explained above in the docs, Debounces are a “pattern in a coding technique that prevents a function from running too many times or an input from triggering multiple times”. The .Touched event fires every time it is tounched, so whenever a player moves on top of that part, it is fired again and again.

You need to add a true or false, or make a player list and check if the player is already in this list. Something like this might work. Here is a example of true and false debounces:

--Other code here
local db = false
hitbox.Touched:Connect(function(hit)
    if db == true then return end
       db = true
		local dmgamount = 7.5
		local hitboxevent = game.ReplicatedStorage.Events.HitBoxEvent
		local character = hit.Parent
		local hithumanoid = character:FindFirstChild("Humanoid")
		if hithumanoid then
			hitboxevent:Fire(dmgamount, hithumanoid)
			else
		end
    task.wait(0.5) -- Wait 0.5 so it doesn't fire again in 0.5 seconds. Change this to what you like if you need longer or shorter times for damage
    db = false
end)

--rest of code here
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.