Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Is There Any Way To Prevent Lag When Using a Touched Event?

OK So I have a script that when an AI/NPC touches it then it fires an event. The problem is that It stands there and waits for the user to give it a command. But when it stands there it is still running the touched event and the Touched event then starts to cause lag and slow the entire game down.

Here is the code if that helps.

Part = script.Parent
Waiting = script.Parent.Waiting
Seat = script.Parent.Seat
SeatNumber = script.Parent.SeatNumber
WaitingInLine = script.Parent.WaitingInLine
local DidHit = false

Part.Touched:connect(function(HIT)
	local TimerStart = HIT.Parent.Moods.TimerStart

	if not DidHit then
		DidHit = true
		
		if HIT.Parent.Monster.Value == true then
			print("Monster")
			--Start Mood Timer
			TimerStart.Value = true
			WaitingInLine.Value = true

			while Waiting.Value == true do

				print("ITs In The While Loop")		
				if Seat.Value == true then	
					HIT.Parent.Destination.Value = SeatNumber.Value 
					Waiting.Value = false
				else
					wait(0.5)	
			end
			wait(0.1)
		end
		wait(3)
		DidHit = false

		else
			print("Human")
		end
	end
end)

The thing is I only want the event to work when the NPC walks into the Object but its constantly firing even when the NPC stands still. Is there any way to make it not do that. ALSO I TRIED DEBOUNCE AND THAT DOESNT WORK BECAUSE THE EVENT STILL FIRES REGARDLESS.

2 answers

When you use a touched event it takes into consideration everything it touches for example the ground it's on.

This code checks if the part it's touched is locked or anchored such as the baseplate, and if it is then the script won't run, and will only run if the part it touched is not anchored or locked like a NPC.

Add this at line 8.

Part.Touched:connect(function(HIT)
if HIT.Locked == true or HIT.Anchored == true then return end

Similarly if you only want a specific part to work when it's touched try entering it's name. This will only allow the script to run if what touched it has that name.

Part.Touched:connect(function(HIT)
if HIT.Name == "yourNPCnameHere" then

You can also add more names.

Part.Touched:connect(function(HIT)
if HIT.Name == "yourNPCnameHere" or HIT.Name == "2ndNPCname" then

Hope this helps !

Make sure the NPC or player in question has it's bodypart's collision detection set to box.

Default collision detection on CSG or meshparts is very detrimental to a game's performance for whatever reason - so it's best practice to set the collision detection to box on NPCs, players, and weapons.

This discussion is preserved as it was. New answers, comments, and votes are closed.