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

Is there a simply way to return two random players?

Asked by 6 years ago
`function ChooseRandomPlayer()
    local GamePlayers = game.Players:GetChildren()

    local ChosenPlayer = GamePlayers[math.random(1, #GamePlayers)] -- The "#" just means the number of things inside that model.
    if ChosenPlayer then
        local player1 = ChosenPlayer
        local ChosenPlayer2 = GamePlayers[math.random(1, #GamePlayers)]
        if player1 == ChosenPlayer2 then
            local ChosenPlayer3 = GamePlayers[math.random(1, #GamePlayers)]
            if player1 == ChosenPlayer3 then
                local ChosenPlayer4 = GamePlayers[math.random(1, #GamePlayers)]
                if player1 == ChosenPlayer4 then
                    local ChosenPlayer5 =       GamePlayers[math.random( > 1,#GamePlayers)]
                    return ChosenPlayer5,ChosenPlayer --
                else 
                    return ChosenPlayer4,ChosenPlayer
                end
            else 
                return ChosenPlayer3,ChosenPlayer
            end
        else 
            return ChosenPlayer2,ChosenPlayer
        end

    end
end`

At the moment I have the script.. - Find one random player and then find another - Check to see if it is the same player - If it is the same player, then check again. If it isn't, return the two players and end. - This cycle repeats 4 more times, considering it is unlikely to find the same player 6 total times...

I feel as if I am being silly in my methods of doing this. Surely there is another, simpler way to find two different random players?

1 answer

Log in to vote
0
Answered by
RayCurse 1518 Moderation Voter
6 years ago

You could use a loop to keep on generating a new random player until the two players selected are different.

function ChooseRandomPlayer()
    local GamePlayers = game.Players:GetChildren()
    if #GamePlayers > 1 then
        local player1
        local player2
        repeat
            player1 = GamePlayers[math.random(1 , #GamePlayers)]
            player2 = GamePlayers[math.random(1 , #GamePlayers)]
        until player1 ~= player2
        return player1 , player2
    end
end
Ad

Answer this question