Help! Laggy script, need to optimise

This script stuns the monster in my game when a bullet touches it, and it works fine, but if I spawn two of these monsters, the game lags for like 5 seconds, is there anything wrong with it?

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!")
				delay(10, function()
					sunny.Humanoid.WalkSpeed = walkSpeed
					sunny.Humanoid.JumpPower = jumpPower
					sunny.KillScript.Disabled = false
					stunAnim:Stop()
					sunny.InAction.Value = false
				end)
			end
		end)
	end
end

How many descendants does “sunny” have?

I’m assuming sunny is the monster. You may not want to go about getting all the descendants of the monster as every single part will respond to anything it’s touching, hence creating lag.

You also may want to add a debounce system. A debounce system could be helpful so when a bullet touches the monster, descendant.Touched is no longer called. Without this, you have no control over the amount of times descendant.Touched is called for all of sunny’s descendants. Here’s my attempt at this system:

function monsterStun() --
	local debounce = false --
	for i, descendant in pairs(sunny:GetDescendants()) do
		if descendant:IsA("BasePart") then
			descendant.Touched:Connect(function(hit)
				if debounce == false then --checking if debounce is not true
					if hit.Parent == game.Workspace.GameAssets.Bullets and sunny.InAction.Value == false then
						debounce = true --setting debounce true
						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!")
						delay(10, function()
							sunny.Humanoid.WalkSpeed = walkSpeed
							sunny.Humanoid.JumpPower = jumpPower
							sunny.KillScript.Disabled = false
							stunAnim:Stop()
							sunny.InAction.Value = false
							monsterStun() --reseting
						end)
					end
				else --debounce is true
					return --stopping Touched function for descendants that no longer need to be touched
				end
			end)
		end
	end
end --
1 Like

I didn’t think of using a debounce, i’ll try that now!

1 Like

I’m glad I could help. Wish you luck on your project! :blue_heart:

1 Like