:Disconnect() troubles

Despite me coding with Roblox for almost a year now, I’ve only started trying out :Disconnect() now. The Developer API page gave a good explanation on how it works, however I could not figure out what was wrong with my code below.

I’ve been tinkering with it for about the last 20 minutes or so, but I always get the same output regardless: attempt to index nil with 'Disconnect'

I cannot figure out what is wrong. My apologies to ask such a cliche question, but where is my error?

-- Objects
local players = game.Players

-- Variables
local amount = 1
local connection 

-- Functions
local function reachAmount()
	local plrCount = #players:GetPlayers()
	if plrCount >= amount then
		-- script.Display.Disabled = false (ignore this line)
		connection:Disconnect()
	end
end

-- Connection
local connection = players.PlayerAdded:Connect(reachAmount)

Thank you for reading this post.

Make sure to set the connection to nil after you disconnect it just to make sure (at least I use to do that), and check if connection ~= nil before trying to :Disconnect() it!

Simple fix:

local function reachAmount()
	local plrCount = #players:GetPlayers()
	if plrCount >= amount then
		-- script.Display.Disabled = false (ignore this line)
		if connection then connection:Disconnect() connection = nil end
	end
end

It’s because you’re redefining the connection variable later in your script. To reference the one you made at the top of the script, remove local.

-- Objects
local players = game.Players

-- Variables
local amount = 1
local connection --> as far as the function is concerned, this will always be nil

-- Functions
local function reachAmount()
	local plrCount = #players:GetPlayers()
	if plrCount >= amount then
		-- script.Display.Disabled = false (ignore this line)
		connection:Disconnect()
	end
end

-- Connection
connection = players.PlayerAdded:Connect(reachAmount)
    --> removed local to reference the previous "connection" variable
2 Likes

This might actually be the correct answer.

Both suggestions work, but I’m marking this the solution as it seems more practical.