Need help optimising code!

This code is too laggy, what can I change that will still detect when a bullet touched the monster, but doesn’t lag?

It works with one monster, but if I add two of them, the game freezes :confused:

for i, descendant in pairs(sunny:GetDescendants()) do
	if descendant:IsA("BasePart") then
		descendant.Touched:Connect(function(hit)
			if hit.Parent == game.Workspace.GameAssets.Bullets and sunny.InAction.Value == false then
				hit.CanTouch = false
				sunny.InAction.Value = true
				local stunAnim = humanoid.Animator:LoadAnimation(sunny.Animate.StunAnim)
				stunAnim:Play()
				sunny.Humanoid.WalkSpeed = 0
				sunny.Humanoid.JumpPower = 0
				sunny.KillScript.Disabled = true
				game.ReplicatedStorage.Events:WaitForChild("gameEvent"):FireAllClients(sunny.Name .. " has been knocked out for 10 seconds!")
				wait(10)
				sunny.Humanoid.WalkSpeed = walkSpeed
				sunny.Humanoid.JumpPower = jumpPower
				sunny.KillScript.Disabled = false
				stunAnim:Stop()
				sunny.InAction.Value = false
			end
		end)
	end
end

The first thing I can recommend if you truly want to optimize your system is to abandon this method of detecting when the bullet hits the monster. It is truly inefficient to run the Touched event on each part of the monster when trying to detect bullets. In fact, it’s actually recommended to not use the BasePart | Roblox Creator Documentation event because of it’s unreliability, especially with fast-moving projectiles. Instead you should try using Raycasting to detect if the bullet hits a part.

In other words, try changing the way you detect if the bullet hits the monster. Instead of trying to detect when something hits the monster, try making it so that you detect when the bullet hits something. And if that something happens to be a descendant of the monster then trigger the function. If you need more info let me know.

3 Likes