How can I detect last player alive wins?

I want to detect when the last player is alive how can I do this? I tried to make a table and put people in the table when a variable in their player is checked true this is inside a server script

server script:

	local plrDead = {}
	print(#plrDead.. " 11")
	repeat
		
		
		
		
	until #game.Players:GetPlayers() - #plrDead == 1 or #game.Players:GetPlayers() == 1 --//repeats until ONE REMAINS

	EndGame()

I’ve wrote a whole system to check players that are alive for you. Make sure you put it in a Server Script.

local Players = game:GetService('Players');
local RunService = game:GetService('RunService');
local alivePlayers = {};

local function getAlivePlayers()
	local Alive = {};
	for Player, IsAlive in next, alivePlayers do
		if IsAlive then
			table.insert(Alive, Player);
		end;
	end;
	return Alive;
end;

for _, x in next, Players:GetPlayers() do
	local Character = x.Character;
	local Humanoid = Character and Character:FindFirstChild'Humanoid';
	if Humanoid and Humanoid.Health > 0 then
		alivePlayers[x] = true;
		Humanoid:GetPropertyChangedSignal'Health':Connect(function()
			if Humanoid.Health <= 0 then
				alivePlayers[x] = false;
			end;
		end);
	end;
end;

local AlivePlayers = {};
repeat wait(1); -- check every 1 second maybe
	AlivePlayers = getAlivePlayers()
until #AlivePlayers < 2;

local LastPlayer = AlivePlayers[1];
if LastPlayer then
	warn('Last player survived:', LastPlayer.Name);
else
	warn'No one survived.';
end;
1 Like

yo why do you got semicolons? Lua doesn’t require that stuff.

you can connect the Humanoid.Died Event or Player:GetPropertyChangedSignal("Team")(assuming you have teams for the alive/dead players) to a code block that removes the player from the alive table then checks if only 1 is left.

It’s about preferences… I use them because that’s how I got used to from C++.

Hey also it works thanks I appreciate it!

1 Like