Many parts of LocalScript only work sometimes

For some reason, there are many parts of my LocalScript that just don’t work sometimes. There are no errors in the output, it just occasionally does nothing. I put a snippet of my code below that could serve as an example for how it pretty much looks like.

spawn(function()
		
		local Switch1 = Puzzle:WaitForChild("Switch1")
		local Red = Switch1:WaitForChild("Red")
		local Blue = Switch1:WaitForChild("Blue")
		local Hitbox = Switch1:WaitForChild("Hitbox")
		local Light = Switch1:WaitForChild("Light")
		local Lasers = Puzzle:WaitForChild("Lasers")
		local Bottom = Lasers:WaitForChild("Bottom")
		local Top = Lasers:WaitForChild("Top")
		local sdebounce1 = true

		Hitbox.Touched:Connect(function(hit)
			local h = hit.Parent:FindFirstChild("Humanoid")
			if h and h == hum and sdebounce1 then
				sdebounce1 = false
				Light.Color = Color3.fromRGB(0, 60, 0)
				script.Switch:Play()
				script.Button:Play()
				
				if Red.Color == Color3.fromRGB(160, 0, 0) then
					Red.Color = Color3.fromRGB(60, 0, 0)
					Blue.Color = Color3.fromRGB(0, 160, 160)
					TS:Create(Bottom, TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out, 0, false, 0), {Position = Vector3.new(0, 9.24, -1015.49)}):Play()
					TS:Create(Top, TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out, 0, false, 0), {Position = Vector3.new(0, 4.24, -1015.49)}):Play()
				else
					Red.Color = Color3.fromRGB(160, 0, 0)
					Blue.Color = Color3.fromRGB(0, 60, 60)
					TS:Create(Bottom, TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out, 0, false, 0), {Position = Vector3.new(0, 4.24, -1015.49)}):Play()
					TS:Create(Top, TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out, 0, false, 0), {Position = Vector3.new(0, 9.24, -1015.49)}):Play()
				end
				
				task.wait(0.6)
				Light.Color = Color3.fromRGB(0, 165, 0)
				sdebounce1 = true
			end
		end)
		
	end)

How would I make the script work 100% of the time?

You could add a slight task.wait() directly below the spawn function, as it would be running incredibly fast just to check if something has been touched. :person_shrugging:

Shouldn’t the Touched event activate whenever the part is touched, not just check if the part is being touched or not?