Touched function

My touched function hits multiple times even though it was debounce on it kinda confused whats wrong with it can anyone help me out?

local AnimTable = {1}
local db = false
Remotes.Click.OnServerEvent:Connect(function(Player)
	if db == false then
		if Player.Character.Settings.Weapons.Katana.Value == true then
			if Player.Character.Settings.Equiped.Value == true then
				db = true
				
				--animations
				if AnimTable[1] == 1 then
					local Attack1 = Player.Character.Humanoid:LoadAnimation(RepStorage.Animations.Katana.KatanaAttack1)
					Attack1:Play(0.2,2,2.5)
					AnimTable[1] = 2
				else
					if AnimTable[1] == 2 then
						local Attack2 = Player.Character.Humanoid:LoadAnimation(RepStorage.Animations.Katana.KatanaAttack2)
						Attack2:Play(0.2,2,2)
						AnimTable[1] = 1
					end
				end
				
				--damage
				local db1 = false
				Player.Character.Katana.Touched:Connect(function(touched)
					if db1 == false then
						db1 = true
						touched.Parent.Humanoid:TakeDamage(30)
						wait(1)
						db1 = false
					end
				end)
				
				
				wait(0.3)
				db = false	
			end
		end
	end
end)

I think I see the problem here.

Each time you call this RemoteEvent, you’re actually creating what’s called a listener object when you call :Connect() on the .Touched event. What this means, in simplest terms, is that you’re binding another function to run when the .Touched event fires. (You can bind multiple functions to the same event, hence the issue.)

By the looks of it, you should be able to fix this issue by disconnecting that specific connection object when it hits something. However, I would recommend restructuring your code, as there’s definitely a better way to do what you’re trying to achieve here.

local touched_listener;
touched_listener = Player.Character.Katana.Touched:Connect(function(touched)
					if db1 == false then
						db1 = true
						touched.Parent.Humanoid:TakeDamage(30)
						wait(1)
                                                touched_listener:Disconnect() --//This function will no longer run when the event fires.
					end
				end)
2 Likes