How can I reduce MoveTo() RunService Lag

The issue is that I have an ability that summons zombies but when there are too much it lags, is there any way to optimize this?

function findNearestTorso()
	local closestTorso = nil
	local closestDistance = math.huge

	for _, descendant in ipairs(workspace:GetDescendants()) do
		if descendant:IsA("BasePart") and descendant.Name == "Torso" then
			local humanoid = descendant.Parent:FindFirstChildOfClass("Humanoid")
			if humanoid and not humanoid:IsDescendantOf(character) and not humanoid:FindFirstChild("ZombieAlly") and not humanoid:FindFirstChild("Dummy") and humanoid.Health>0 then
				local distance = (descendant.Position - character.HumanoidRootPart.Position).Magnitude
				if distance < closestDistance then
					closestTorso = descendant
					closestDistance = distance
				end
			end
		end
	end

	return closestTorso, closestDistance
end

local walkconnect= RunService.Heartbeat:Connect(function()
		humanoid.WalkSpeed=speed
		torso,distance=findNearestTorso()
		if torso and humanoid.Health>0 then
			local hum=torso.Parent:FindFirstChild("Humanoid")
			if hum then
				if hum.Health>0 then
					local humanoidRootPart = character.HumanoidRootPart
					local newLookVector = (torso.Position - humanoidRootPart.Position).Unit
					local newCFrame = CFrame.new(humanoidRootPart.Position, humanoidRootPart.Position + newLookVector)
					character:SetPrimaryPartCFrame(CFrame.lookAt(humanoidRootPart.Position, torso.Position * Vector3.new(1, 0, 1) + humanoidRootPart.Position * Vector3.new(0, 1, 0)))
					local targetPosition = (torso.Position + (character.HumanoidRootPart.Position - torso.Position).Unit * 3.5)
					local newPosition = character.HumanoidRootPart.Position:Lerp(targetPosition, math.min(1, distance / 3.5))
					humanoid:MoveTo(newPosition, character.HumanoidRootPart)
				end
			end
		end
end)

Firstly, you don’t need to search for a target 60 times per second. Try lowering it to 10 times a second.

Secondly, you’re getting all of the descendants of workspace in the findNearestTorso function, which is extremely costly – that’s several thousands of instances. You’re also doing it every frame, which is even worse. Instead, use CollectionService to tag each character model that the zombies can target (e.g. “ZombieTarget”), and then loop through all the tagged character models to find the nearest target. That’ll reduce the amount of instances you’re checking from a couple thousand to under a hundred.

1 Like

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