How do I disconnect this function?

I am trying to figure out how to stop this prompt from getting spammed, I know I need to disconnect this CheckPart() function but I do not know how.

local RunService = game:GetService('RunService')

--for i,v in pairs(workspace.Resources:GetChildren()) do
--	local Main = v:FindFirstChild('Main')
	
--	if (game.Players.LocalPlayer:DistanceFromCharacter(Main) <= 10) then
--		DisplayPrompt()
--	end
	
--end

local touchPart

function DisplayPrompt(mainObject)
	local prompt = game.ReplicatedStorage.Assets.Prompt:Clone()
	prompt.Parent = mainObject
	local offset = Vector3.new(0,0,5)
	prompt.CFrame = mainObject.CFrame*CFrame.new(offset)
end

function CheckPart()
	RunService.RenderStepped:Connect(function()
		for i,v in pairs(workspace.Resources:GetChildren()) do
			local mainObject = v:FindFirstChild('Main')

			if (game.Players.LocalPlayer:DistanceFromCharacter(mainObject.Position) <= 10) then
				DisplayPrompt(mainObject)
			end

		end
	end)
end

CheckPart()

1 Like

You can actually store the connection in a variable and disconnect it later when needed, like so:

local RunService = game:GetService("RunService")

local connection = RunService.RenderStepped:Connect(function(delta)
    -- your code down here, etc
end)

-- Somewhere later in the code

connection:Disconnect()

Hope this helps!

1 Like

Try this out, using a debounce you could easily stop the spam

local touchPart
local inZone = false

function DisplayPrompt(mainObject)
	local prompt = game.ReplicatedStorage.Assets.Prompt:Clone()
	prompt.Parent = mainObject
	local offset = Vector3.new(0,0,5)
	prompt.CFrame = mainObject.CFrame*CFrame.new(offset)
end

function CheckPart()
	RunService.RenderStepped:Connect(function()
		for i,v in pairs(workspace.Resources:GetChildren()) do
			local mainObject = v:FindFirstChild('Main')

			if (game.Players.LocalPlayer:DistanceFromCharacter(mainObject.Position) <= 10) then
				if inZone == false then
					inZone = true
					DisplayPrompt(mainObject)
				end
			else
				inZone = false
			end

		end
	end)
end

CheckPart()


It still spams. The debounce does not work in this case because the player still meets that if statement, being within 10 studs of that part. So as long as the player is there it’s going to continue cloning.

The solution to disconnecting functions is what @Courageous_Canister suggested, although if you want to disconnect the function inside itself, you need to define the variable before the function:

local connection
connection = RunService.RenderStepped:Connect(function(delta)
	connection:Disconnect()
end)
1 Like