I have created a script from scratch that detects whether or not a NPC's sword hits another enemy NPC. However if the NPC's sword touches, let's say, a friendly NPC, the function fires rapidly causing the entire game to experience minor lag.Unfortunately, my game averages around 100+ NPCs at a time which make the game lag even more. Also when you mix in the NPCs moving whilst their swords are touching friendlies, the function fires even more. I need help on reducing this lag or even stopping it all together.
TL;DR = My script's function rapidly fires when it hits a friendly NPC. The function rapidly firing causes major lag. I need a cooldown or some sort for the function itself.
Below is my script:
local rs = game:GetService("ReplicatedStorage")
local damage = rs.R_KnightDamage.Value
local cooldown = 1.15
local debounce = false
local sword = script.Parent
local blade = sword.Handle
local currentHuman = sword.Parent:FindFirstChildOfClass('Humanoid')
local attackAnim = currentHuman:LoadAnimation(blade.Attack2)
local currentTeam = currentHuman.Parent:FindFirstChild('Team')
function swordTouched(target)
if (target.Name == "Head" or target.Name == "Left Leg" or target.Name == "Right Leg" or target.Name == "Left Arm" or target.Name == "Right Arm") then -- PART CHECKER
local human = target.Parent:FindFirstChildOfClass('Humanoid')
if (human) then
if (currentHuman.Health ~= 0) then
if (target.Parent:FindFirstChild('Team')) then
local enemyTeam = target.Parent:FindFirstChild('Team') -- PREVENTS TEAM-KILLING
if (enemyTeam.Value ~= currentTeam.Value) then
if (debounce == false) then debounce = true
human:TakeDamage(damage)
attackAnim:Play()
local randomSound = math.random(1,2) -- SOUND MODULE
if randomSound == 1 then blade.s1:Play()
else blade.s2:Play()
end
wait(cooldown)
debounce = false
end
end
end
end
end
end
end
blade.Touched:Connect(swordTouched)

2 comments
Lag has definitely decreased substantially. However now something else in my game is causing lag. Thanks!
Great! If you need help with that make sure to post it here.