An if statement running more than once

so i’ have been trying to make a combat system, and was struggling with an issue, I could find the source, but I couldn’t come up with a solution.

this is the function that runs when you hit something (this is just a part of the code)

connection = player.Character.RightHand.Touched:Connect(function(hit)
				if hit and hit.Parent then
					local enemyHumanoid = hit.Parent:FindFirstChild("Humanoid")
					if enemyHumanoid and not humanoidsThatHaveBeenHit[enemyHumanoid] then -- sees if "hit" is a humanoid, and also checks if it wasnt hit before, to avoid dealing the damage again
						if enemyHumanoid:FindFirstChild("IsBlocking").Value == false then -- sees if the player isn't blocking damage
							humanoidsThatHaveBeenHit[enemyHumanoid] = true
							enemyHumanoid:TakeDamage(10)
							print("hit") -- this prints once, so there is no issue here
							
						elseif enemyHumanoid:FindFirstChild("IsBlocking").Value == true then -- this is the issue
							print("blocked") -- this prints more than once, atleast 5 times. it should only print once
							-- rest of the code
						end
					end
				end
			end)

“solutions” i tried but didnt work :

I tried using else if instead of elseif
using a bool value instead of using humanoidsThatHaveBeenHit

Well yeah, there’s a logical flaw to your code. You only use your debounce table when the value is true, hence when the value is false, the touched event can be spammed. Just move your debounce table outside of the if statement. And yeh an if statement would look more cleaner since you’re using a boolean (either can be true or false only)

1 Like