How do I detect a player leaving without the Players.PlayerLeaving event?

So I have a boss fight system in my game which seems to work fine, except when a player leaves while fighting a boss. When this happens, the boss fight script errors and does not reset the IsPlayerFightingBoss value to false, making it so that nobody else can fight a boss until the server resets.
The problem is, I don’t know how to tell if a player leaves. Here is my code that happens while the boss is being fought:

	local playerIsntNil = true
		
while playerIsntNil and player.Character:FindFirstChildOfClass("Humanoid").Health > 0 and boss:FindFirstChildOfClass("Humanoid").Health > 0 do

	wait()
	if player == nil then
		
		playerIsntNil = false
		break
		
	end

end

The reason it’s a while loop is because I am waiting for the boss to end. I have tried if not player then and it doesn’t work. I have tried adding a print statement, and have determined that it is restarting the loop before detecting if the player is nil, meaning that player is nil and :FindFirstChildOfClass will error, which is exactly what is happening.

Basically, I am looking for a way to find if player == nil, and I cannot figure it out, and I cannot use Players.PlayerLeaving the way my code is set up.

EDIT: Now the boss is the problem, managed to add a players.PlayerRemoving event. Returning the same error

1 Like

Just verify the specified player exists in the game world, and you should be good.

local function doesPlayerExist(playerName)
local player =  game:GetService("Players"):FindFirstChild(playerName)

return player and player.Character
end

Wrap that in a condition for your boss handler to determine if certain code should execute.

3 Likes

Managed to get it working. Still probably a good idea to use that as a backup.

1 Like

Please set this post as Solved. :+1:

You could use the ChildRemoved event on Workspace - or on Players [depends on your situation/choice ] if you want to, you’ll just need to make sure the child that has been removed was a player, and not an npc or a part.

But, as @C_Sharper wrote above, you could use his function to check if the player has left the server.

Idk what post to mark though, which one should I use?

1 Like

Set it to the one that helped you the most.

Mark @C_Sharper 's as the solution. Since he replied to you first with a good answer.

2 Likes