Hi! I’m working on a new game, and it features a round system that stops only when all the players in the current game have died. However, I’ve encountered a bug recently: if a player leaves during the round, they are still counted as “alive” by the game, causing the round not to stop when everybody else dies. I have no idea how to fix this issue and could really use some help.
Heres what I have so far:
function handleRound()
local plrsAlive = {}
for _, plr in pairs(game.Players:GetPlayers()) do
if plr.Character and plr.Character.Humanoid.Health > 0 then
table.insert(plrsAlive, plr)
plr.Character.Humanoid.Died:Connect(function()
table.remove(plrsAlive, table.find(plrsAlive, plr))
end)
end
end
for i = 1, 300 do
task.wait(1)
if #plrsAlive == 0 then
break
end
end
task.wait(5)
end
Thank you for reading all the way to the end, I appreciate the help.
Your code will error if the player wasn’t in the game when they left, because table.find will return nil since it won’t be able to find the player in the plrsAlive table.
Fixed code:
--//Services
local Players = game:GetService("Players")
--//Tables
local plrsAlive = {}
--//Functions
local function handleRound()
--//Reset plrsAlive table
table.clear(plrsAlive)
for _, plr in ipairs(Players:GetPlayers()) do
local character = plr.Character
local humanoid = character and character:FindFirstChildWhichIsA("Humanoid")
if humanoid and humanoid.Health > 0 then
table.insert(plrsAlive, plr)
humanoid.Died:Connect(function()
table.remove(plrsAlive, table.find(plrsAlive, plr))
end)
end
end
for i = 1, 300 do
task.wait(1)
if #plrsAlive == 0 then
break
end
end
task.wait(5)
end
Players.PlayerAdded:Connect(function(player)
local playerIndex = table.find(plrsAlive, player)
if playerIndex then
table.remove(plrsAlive, playerIndex)
end
end)
Let’s say that the game already started, and in the middle of the round, a new person joins. That new person is not added to the plrsAlive table, so if he leaves before the round ends, your function will error because he was not part of that table in the first place.
Oops, I meant to put PlayerRemoving instead of PlayerAdded, here:
--//Services
local Players = game:GetService("Players")
--//Tables
local plrsAlive = {}
--//Functions
local function handleRound()
--//Reset plrsAlive table
table.clear(plrsAlive)
for _, plr in ipairs(Players:GetPlayers()) do
local character = plr.Character
local humanoid = character and character:FindFirstChildWhichIsA("Humanoid")
if humanoid and humanoid.Health > 0 then
table.insert(plrsAlive, plr)
humanoid.Died:Connect(function()
table.remove(plrsAlive, table.find(plrsAlive, plr))
end)
end
end
for i = 1, 300 do
task.wait(1)
if #plrsAlive == 0 then
break
end
end
task.wait(5)
end
Players.PlayerRemoving:Connect(function(player)
local playerIndex = table.find(plrsAlive, player)
if playerIndex then
table.remove(plrsAlive, playerIndex)
end
end)