Issue with .touched

I have code for my enemy, it works fine however the big problem is that while using .touched, it kills the player immediately, this is because when the enemy is coming in contact with the player the .touched event happens hundreds of times, is there any other way I could handle the player coming in contact with the enemy without using the .touched event?

	for _, Part in ipairs(tank:GetChildren()) do
				if Part:IsA("Part") then 
					Part.TouchEnded:Connect(function(plrpart)
						if plrpart.Parent and plrpart.Parent:FindFirstChild("Humanoid") and plrpart.Name ~= "Baseplate" then 
							plrpart.Parent.Humanoid:TakeDamage(damage)
							print("test")
						end
					end)
				end
			end
		end

make a cooldown… It fires a lot because a part of the tank touches every part of the player’s character…

local Cooldown, CooldownTime = false, 1

if not Cooldown then
    Cooldown = true
    task.wait(CooldownTime)
    Cooldown = false
end

Hello there!

The best way to go on about this is to add each bullet that registered a hit to an “already registered” or invalid list, while still allowing new bullets to not be on an active cooldown, feel free to copy and paste this:

local InvalidBullets = {} -- Table to keep track of bullets that have already registered

for _, Part in ipairs(tank:GetChildren()) do
	if Part:IsA("Part") then 
		Part.TouchEnded:Connect(function(plrpart)
			if plrpart.Parent and plrpart.Parent:FindFirstChild("Humanoid") and plrpart.Name ~= "Baseplate" then 
				local bullet = plrpart.Parent
				if not InvalidBullets[bullet] then -- Check if the bullet is already registered
					plrpart.Parent.Humanoid:TakeDamage(damage)
					print("test")

					InvalidBullets[bullet] = true -- Adding the bullet to a list, making it invalid
				end
			end
		end)
	end
end

Please let me know if this resolved your issue!

Sincerely,
Artyom.

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