Loop causing lag help

How can I stop this from lagging out my server??

local function GetTouchingParts(part)
	local Connection = part.Touched:Connect(function() end)
	local Results = part:GetTouchingParts()
	Connection:Disconnect()
	
	return Results
end

spawn(function()
	while wait() do
		for _, touching in pairs(GetTouchingParts(Character.PrimaryPart)) do
			if touching.Parent == Region3s then
				if touching.Name == 'CampSite' then
					print(3)
					TaskComplete:FireServer('Go camping')
					break
				end
			end
		end
	end
end)

It’s inside a spawn function as it’s in a module, and a while loop wont return the module. And a while loop because I need it constantly checking if player is touching said part.

I seem to see something unusual you have touching.Parent.Name and touching.Parent in the same logic section.
Isn’t the Parent name the same as the Parent value?

1 Like

Ye pasted in the broken code, edited with current working code

perhaps you can combine the two ifs into one with an and to separate the two value checks.
One less logic step to run.

Reason I haven’t done that is further down the track I plan on having more parts

if touching.Parent == Region3s then
	if touching.Name == 'CampSite' then

	elseif touching.Name == 'Part2' then

    end
end

etc

Not surprised this is causing lag, considering you’re having your code check for physically intersected parts in a minimal-interval loop and subsequently connecting several empty Touched listeners with no debounces.

A less expensive method would be to check the position of the character’s root part relative to the campsite or some kind of proxy part that determines the area a player needs to be in to be considered in the camping zone. This can be done in two ways:

  • Create a Region3 around the site and check constantly if the root part is inside this Region3 (super inexpensive check of whether one position is inside a region or not)

  • Create an invisible part below the site (under the map) and downcast downwards, using a whitelist towards that part and check if an intersection with that part can be found

2 Likes

Is there a special reason in your case that prevents you from using the Touched Event, which is far easier on the server?

You generally don’t want to poll using wait() if you can use Events (which I’m guessing you can, because you can also use TouchEnded to see when the touch stopped).

I strongly recommend you read Avoiding wait() and why until you feel like you understand it:

Why not just use the touch listener? It seems like you are waiting for a part to touch the Character’s PrimaryPart which you can just detect using Touched.

1 Like