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
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