Disconnecting a function

Hello,

So today as I was scripting, I came into this weird error.

What I’m trying to achieve here is to disconnect a function once a game timer is over.

Now the following code does seem to work, but it is a bit glitchy and sometimes works and if it does, it is delayed after once the player falls to the void (once the map destroys itself)

here is the bit of code:

	deathconnect = player.CharacterAdded:Connect(function(char)
					local random_melee = meleefolder[math.random(1,#meleefolder)]:Clone()
					local random_ranged = rangedfolder[math.random(1,#rangedfolder)]:Clone()
					local random_special = specialfolder[math.random(1,#specialfolder)]:Clone()

					random_melee.Parent = player.Backpack
					random_ranged.Parent = player.Backpack
					random_special.Parent = player.Backpack
					
					repeat task.wait() until char:IsDescendantOf(workspace)
					char.HumanoidRootPart.CFrame = CFrame.new(availablespawnpoints[1].Position + Vector3.new(0,5,0))
					table.remove(availablespawnpoints, 1)
					
					spawn(function()
						print("disconnected deathconnect")
						task.wait(game_timer)
						deathconnect:Disconnect()
					end)
				end)

I’m willing to show all of the code if it’s necessary.

Now what I have also tried is to wait til the game_timer is over, and then disconnect the function. But doing so would only make the error go away for 1 Player.

Any help is appreciated.

This could be somehow related to how Roblox handles events now.
A not too recent update switched up the order of events and function executions.

Instead of connecting/disconnecting events, try simply putting a script in the player and delete the script when the round or game is over and see if that helps.

Connecting/disconnecting events can be a little weird sometimes so I try not to do it too much unless I know what I’m doing.