Can I optimize this any more? I try to make two functions disconnect when one is ran

for i, player in pairs(Players:GetPlayers()) do
		AlivePlayers[i] = player

		local c1: RBXScriptConnection?, c2: RBXScriptConnection?
		local function died()
			AlivePlayers[i] = nil

			if c1 then
				c1:Disconnect()
			end

			if c2 then
				c2:Disconnect()
			end

			c1 = nil
			c2 = nil
		end

		c1 = player.Character:WaitForChild("Humanoid").Died:Once(died)
		c2 = player:GetPropertyChangedSignal("Parent"):Once(died)
	end

I don’t know how to explain it more, I’m trying to make an alive players table and I want it to remove the player if they die or leave, but if one happens I want it to disconnect the other since if they left, they don’t exist anymore and it’ll just be connected forever. And if they die, they aren’t in the table anymore.

So I need a way to disconnect them both but I don’t think my way is good.

1 Like

I’d be more partial to having a single Players.PlayerRemoving connection handle all cases of Players leaving mid-game. Is there any particular reason why you prefer using the indices of the array returned from GetPlayers() for lookup, as opposed to the Player instances themselves?

I dunno, if they left, then wouldn’t it leave the connection for their character dying still there? I guess you’re right either way.

The connection on the humanoid woudn’t leak (even if you don’t explicitly destroy your characters), so long as the connected function doesn’t reference back (directly or indirectly) to that same humanoid. When players leave game, their characters will be removed, and assuming the references aren’t cyclic due to the edge-case I just explained, there shouldn’t be any issue. You could always clear the connections after every match, if you were particularly concerned–but in this case it simply wouldn’t be necessary (unless of course you plan on recycling the same characters round-to-round as opposed to killing them off).

1 Like

What does the question marks after RBXScriptConnection mean?

He’s typecasting meaning that the variable will be storing a RBXScriptConnection and the question mark means the connection could also be nil/connection doesn’t exist. I’ve explained in an easy to understand way hope you get it

1 Like

Thank you so much for explaining! I get it now!

One question though:

Is it better to include a question mark when typechecking in case the type is nil? If it is nil, will an error be thrown?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.