So the below code, it lags like crazy over time. But as soon as I add the “print(“DELAY”)” command it stops lagging. I have no idea why? Like as soon as I comment that out, it’s back to lagging?
local function findTargets()
--print("DELAY")
-- Do a new search region if we are not already searching through an existing search region
if not searchingForTargets and tick() - timeSearchEnded >= SEARCH_DELAY then -- search delay
searchingForTargets = true
-- Create a new region
local centerPosition = Zombie.humanoidRootPart.Position
local topCornerPosition = centerPosition + Vector3.new(ATTACK_RADIUS, ATTACK_RADIUS, ATTACK_RADIUS)
local bottomCornerPosition = centerPosition + Vector3.new(-ATTACK_RADIUS, -ATTACK_RADIUS, -ATTACK_RADIUS)
searchRegion = Region3.new(bottomCornerPosition, topCornerPosition)
searchParts = Workspace:FindPartsInRegion3(searchRegion, Zombie.instance, math.huge)
newTarget = nil
newTargetDistance = nil
-- Reset to defaults
searchIndex = 1
end
if searchingForTargets then
-- Search through our list of parts and find attackable humanoids
local checkedParts = 0
while searchingForTargets and searchIndex <= #searchParts and checkedParts < MAX_PARTS_PER_HEARTBEAT do
local currentPart = searchParts[searchIndex]
if currentPart and isInstaceAttackable(currentPart) then
local character = currentPart.Parent
local distance = (character.HumanoidRootPart.Position - Zombie.humanoidRootPart.Position).magnitude
-- Determine if the charater is the closest
if not newTargetDistance or distance < newTargetDistance then
newTarget = character.HumanoidRootPart
newTargetDistance = distance
print(newTarget, "yes")
else print ("no")
end
end
searchIndex = searchIndex + 1
checkedParts = checkedParts + 1
end
if searchIndex >= #searchParts then
target = newTarget
--print(target,"this is name")
--print(newTargetDistance)
searchingForTargets = false
timeSearchEnded = tick()
end
end
end
while true do
wait()
onHeartbeat()
end