Still have questions? Join our Discord server and get real time help.
1

# How do I stop my script from lagging when it detects the NPC's sword being touched rapidly?

Edited 6 months ago

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 currentHuman = sword.Parent:FindFirstChildOfClass('Humanoid')
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()
end
wait(cooldown)
debounce = false
end
end
end
end
end
end
end



0

I'd say the problem is the sword is making way too many checks every second it is touching which reduces performance a lot. If you look at it, your code has about 7 if's and about 4 or's.

To fix this problem, I would personally firstly check if the player is on the other team or not. If he is, it will do the other checks. If it's not, then it will do only that check.

Also, consider using and.

Example:

if (human)  and (currentHuman.Health ~= 0) and etc.. then