.Touched stacking hits

I’m making a sword and I’m using the .touched function as the hitbox. But there is a bug within the sword that stacks the hits of the sword and when it touches another rig/player all of those stacked hits register.

It’s hard to explain but hopefully this should be clear.

I’ve tried making a different styled hitbox (like raycasting) but it got too complicated and messy that I just resorted back to .touched

Here is the code to my hitbox

local function Hitbox()
	local Sword = Tool.Handle
	local Character = Tool.Parent
	local plr = game.Players:GetPlayerFromCharacter(Tool.Parent)
	local HasHit = false
	
	Sword.Touched:Connect(function(hit)
		if HasHit == false then
			if hit.Parent == Character then -- To avoid damaging the player wielding the sword
				return
			else
				local Humanoid = hit.Parent:FindFirstChild("Humanoid")

				if Humanoid then
					Humanoid:TakeDamage(5)
					HasHit = true
					
					GiveHits(Character)

					local SoundsFolder = script.Parent.Sounds:GetChildren()
					local Sound = SoundsFolder[math.random(1, #SoundsFolder)]

					Sound:Play()
				end
			end
		end
	end)
end

EventsFolder.ClientToServer.OnServerEvent:Connect(function(plr)
	if M1Turn == 1 then
		Tool.Handle.Trail.Enabled = true
		Tool.Handle.Slash.TimePosition = 0.3
		Tool.Handle.Slash:Play()

		local Animation = M1sFolder.Turn1
		local Hum = plr.Character.Humanoid

		local Animtrack = Hum:LoadAnimation(Animation)
		Animtrack:Play()
		
		Animtrack:GetMarkerReachedSignal("Hit"):Connect(function()
			Hitbox()
		end)

		Animtrack.Stopped:Wait()
		
		M1Turn += 1
		
		EventsFolder.ServerToClient:FireClient(plr)
		Tool.Handle.Trail.Enabled = false
1 Like

the problem is when you first activate the tool it will attach Sword.Touched:Connect(function(hit) and did not disconnect the touch event you can fix this by creating connection when start attacking then disconnecting it when finish attacking

you can find example of it here: What are connections, and how do they work?

2 Likes

you could add a debounce so the event can only trigger once until some time has passed like in this example:

local debounce = false

function onTouch()
--[[ so if we’ve touched the
hit box in the last 5 seconds,
it’ll stop running the code
]]
   if debounce == true then
      return
   end
   debounce = true
--[[ and yknow all your code
would be here then you wanna
5sec cooldown
]]
   task.wait(5)
   debounce = false
end

[INSTANCE NAME].Touched:Connect(onTouch)

obv I just provided an example but I can rewrite your code to tweak it if you need more help

2 Likes

It worked like a charm thank you so much!!!