Getting giant lag spikes when touching brick

what i have been getting is that when i touch this with a brick i want it to detect or a player that isnt supposed to activate it creates lag during studio. this is for a power up when you run it over it will explode with particles also the particles do not cause lag i have tested it. :grin:

``

local RunService = game:GetService(“RunService”)

local Players = game:GetService(“Players”)

local part = script.Parent

toggle = true

Cooldown = false

while wait() do
if Cooldown == false then
part.Hitbox.Touched:Connect(function(touched)

if Cooldown == false then
if touched.Name == "Hitbox" then
	
    if  touched.Parent.Player then
		local Id = touched.Parent.Player.Value
		
	
	
		if toggle then
			toggle = false
			part.Effect.Enabled = true
			part.Effect1.Enabled = true
			script.Parent.Sound:Play()
			script.Parent.Sound1:Play()
			part.Light.Enabled = true
			wait(0.25)
			part.Light.Enabled = false
			part.Effect.Enabled = false
			part.Effect1.Enabled = false
			part.Transparency = 1
			part.Picture.Transparency = 1
			part.Picture1.Transparency = 1
			wait(5)
				part.Transparency = 0
			part.Picture.Transparency = 0
			part.Picture1.Transparency = 0
			part.Light.Enabled = true
			toggle = true
		
		end
	
			
		end
	end	
end

Cooldown = true
wait(0.1)
Cooldown = false
end)


end

end
``

i am unsure if its just my computer or not i get lag spike in ping and fps when in studio testing and im averaging in 60 fps on lowest settings.

You’re wrapping the touched event in a while loop, spawning multiple running threads nearly every frame.

I don’t think you need to do that.

1 Like

The issue is you have this in a

while wait() do -- Don't call wait in the conditional part tho

end

wait, without arguments, yields for about 1/30th of a second. So this means you are creating 30 connections per second. Remove the while loop. It is not doing anything useful here.

1 Like

Surprisingly that fixed it thanks. earlier it wasnt activating without the while loop. thanks!

im unsure what you mean by threads.