How can I stop using run service here?

Hello, so I have a module. The problem is with performance, under some circumstances performance can significantly drop. I believe it’s with the run service part. My one question, is there a different way I can make it repeat without while loops or run service?

RunService.Stepped:Connect(function() --- entered preset

		if self:GetState() == true then

			local NewHitbox = CreateWithRange:Create(StartingPos, Range, Overlap_Params)

			for i,v in pairs(NewHitbox) do
				if not table.find(OldHitbox, v) then
					EnteredEvent:Fire(v)
				end

			end

			OldHitbox = NewHitbox
		else
			error("Cannot use the preset entered without starting a hit box. To start the hit box do: hitbox:Start()")	
		end

Any help is appreciated!!

1 Like

Create a Connection, then check when you want to exactly Disconnect the function to stop listening for the Stepped Event

local RunService = game:GetService("RunService")
local Connection
local function CheckHitbox() -- Call "Disconnect()" whenever you want to stop listening for this function

	if self:GetState() == true then

		local NewHitbox = CreateWithRange:Create(StartingPos, Range, Overlap_Params)

		for i,v in pairs(NewHitbox) do
			if not table.find(OldHitbox, v) then
                Connection:Disconnect()
				EnteredEvent:Fire(v)
			end
		end
			OldHitbox = NewHitbox
		else
            Connection:Disconnect()
			error("Cannot use the preset entered without starting a hit box. To start the hit box do: hitbox:Start()")	
		end
    end
end

Connection = RunService.Stepped:Connect(CheckHitbox)

I’m not sure when exactly you wanna stop looping though

1 Like

I will try this, thank you for saying this