Signalling system creating a lot of lag

Hi y’all. I’m trying to write a fixed-block signalling system (like that of TTC) that uses Touch/TouchEnded events to detect when a train has entered/left a block (see the below script for current implementation).

local touchDebounce: boolean = false
local endDebounce: boolean = false

function touchy()
	print("touched")
end

function endTouchy()
	print("no longer touchy")
end


local touchConnection
local endConnection

function connectTouch()
	touchConnection = script.Parent.Touched:Connect(function(part)
		if part.Name:lower() == "trgsen" and not touchDebounce then
			touchDebounce = true
			touchConnection:Disconnect()
			touchy()
			wait(2)
			connectEnd()
			touchDebounce = false
		end
	end)
end

function connectEnd()
	endConnection = script.Parent.TouchEnded:Connect(function(part)
		if part.Name:lower() == "trgsen" and not endDebounce then
			endDebounce = true
			endConnection:Disconnect()
			endTouchy()
			wait(2)
			connectTouch()
			endDebounce = false
		end
	end)
end

connectTouch()
connectEnd()

Below is a video of how it should work in theory. Yellow brick, named trgsen, touches the red brick, the above script’s parent, printing “touched” and disconnecting the touch event (to hopefully not lag the game out). When it leaves, prints “no longer touchy” and reconnects the touch event. robloxapp-20240102-1603233.wmv (1.1 MB)

This is great in theory. In practice, though, it creates a TONNE of lag [when implemented with an actual train of a few hundred parts]. The console only logs one “touched” event but the game lags to hell as if the event is firing several hundred times per second. Any idea why this might be?

Edit: To note, the track below the sensor has CanTouch disabled. The only thing that is firing the touch event is the trgsen, which, in the actual implementation on the train, is a brick slightly bigger than the train to ensure it touches first.

Edit 2: There is no script in “trgsen”. Everything is being handled in the sensor (red brick).

1 Like