Huge lag on a traffic light sensor script

Hi!
I’m experiencing a problem of which when a seat or a vehicle seat hits the sensor (for the traffic lights), there are major lag spikes on many devices.

  1. What do you want to achieve?
    Reducing lag/optimizing on a sensor script

  2. What is the issue?
    HUGE lag when a vehicle seat hits the sensor

  3. What solutions have you tried so far?
    Making functions local, using task.wait(), and more.

local function AddSensor(sensor)
	sensor.Transparency = 1
	local distance
	if sensor.Size.X > sensor.Size.Z then distance = sensor.Size.X else distance = sensor.Size.Z end
	sensor.Touched:Connect(function(hit)
		local b = false
		local s = script.Parent.MasterScript.Triggers:FindFirstChild(sensor.Name)
		if hit:IsA("Seat") or hit:IsA("VehicleSeat") then
			hit.AncestryChanged:Connect(function() b = true end)
			repeat s.Value = true task.wait(.1)
			until b == true or math.ceil((sensor.Position - hit.Position).magnitude) >= distance
			s.Value = false
		end
	end)
end


local sensors = script.Parent.Sensors:GetChildren()
for i = 1,#sensors do if sensors[i].ClassName == "Part" then AddSensor(sensors[i]) end end

You got no debounce, so your Touched event can activate tens if not hundreds of times each second. :slight_smile:

1 Like

:expressionless:
I hope it works…

local function AddSensor(sensor)
	
	local deb = false
	sensor.Transparency = 1
	local distance
	if sensor.Size.X > sensor.Size.Z then distance = sensor.Size.X else distance = sensor.Size.Z end
	sensor.Touched:Connect(function(hit)
		if not deb then
			deb = true
		
		local b = false
		local s = script.Parent.MasterScript.Triggers:FindFirstChild(sensor.Name)
		if hit:IsA("VehicleSeat") then
			hit.AncestryChanged:Connect(function() b = true end)
			local hit:VehicleSeat = hit
			
			
			
			hit:GetPropertyChangedSignal("Position"):Connect(function()
				if  math.ceil((sensor.Position - hit.Position).Magnitude) >= distance then
					s.Value = false
				end
			end)
			repeat s.Value = true task.wait(.1)
			until b == true
			s.Value = false
			end
			deb = false
		end
	end)
end


local sensors = script.Parent.Sensors:GetChildren()
for i = 1,#sensors do if sensors[i].ClassName == "Part" then coroutine.wrap(AddSensor)(sensors[i]) end end

Remember to disconnect connections, if they become obsolete at some point in the process. :slight_smile:

1 Like