Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to make a when all players in team dies will run next code?

Asked by
Diltz_3 75
6 years ago

I want to make script when all players in team dies will be run next code, when I tried I'm tested and code starts if one player will die in team not all what's my mistake?

ServerScript

    for i,b in pairs(game.Teams.Playing:GetPlayers()) do
        b.Character:FindFirstChild("Humanoid").Died:connect(function()
            wait(8)
            workspace.Map:ClearAllChildren()
            if Players.Value < 2 then
                Message.Value = "2 Players are needed!"
                GameActive = false
            else
                gamestart()
                Message.Value = "Intermission..."
            end
        end)
    end

1 answer

Log in to vote
0
Answered by
fredfishy 833 Moderation Voter
6 years ago

Something like this should work?

Basically, your problem is that your event fires when ANY humanoid dies. You need to keep track of how many there are, decrement a counter when somebody dies, and when there are 0 remaining, the team is eliminated.

function checkEliminated(counter, team)
    if counter.Value <= 0 then
        -- team eliminated
    end
end

function beginRound()
    for _, team in pairs(game:GetService("Teams"):GetChildren()) do
        if team:IsA("Team") then
            -- Create a global counter of remaining players in a team
            local aliveCounter = Instance.new("IntValue", team)
            aliveCounter.Name = "PlayersRemainingCount"

            -- Get all the players in this team
            local teamPlayers = team:GetPlayers()
            aliveCounter.Value = #teamPlayers

            for _, p in pairs(teamPlayers ) do
                if p.Character and p.Character:FindFirstChild("Humanoid") then
                    -- When they die, decrement the global counter
                    local conn = p.Character.Humanoid.Died:Connect(function()
                        aliveCounter.Value = aliveCounter.Value - 1 -- Decrement counter
                        conn:Disconnect() -- Make sure that dying again doesn't decrease the counter until the next round
                        checkEliminated(aliveCounter, team)
                    end)
                else
                    -- If they don't have a character, or they don't have a humanoid, they're already dead
                    aliveCounter.Value = aliveCounter.Value - 1
                    checkEliminated(aliveCounter, team)
                end
            end
        end
    end
end
Ad

Answer this question