How to get 2 random players from a specific team?

I’ve tried many ways to get 2 random players from a team, but didn’t work, help please

2 Likes
  1. create a table and name it whatever u want
  2. loop trough each player and check there team (or not)
  3. if they are in the given team add them into table or whatever
  4. use math.random to get random value from table

example :

local totalteamstable = {}

--// this script will add all players in the same team
for index,player in pairs(game.Players:GetPlayers()) do --// loop trough each player
if player.Team = "Teamname" then --// we can also check their team color instead of teamname
table.insert(totalteamstable,v) --// add the player into the table
end
end

--// get random player from the table
local function  getrandomplayerfromteam() --//  using function so code doesn't look messy

local randomplayer = totalteamstable[math.random(1,#totalteamstable)] --// basically a random number represents a table index and  we  get the value that's stored in that index

--// you can also remove the chosen player from the table  by using table.remove to avoid same player being chosen

return randomplayer  --// return the random player
end

local randomplayerfromteam = getrandomplayerfromteam()  --// we assume that theirs more than 0 objects in table (if theres nothing in table the function will return nil)

if u want to do similar thing with all players regardless what team they are on u can just remove team check

also i wrote this code on devforum so it might not work

local function GetPlayersFromTeam(Team: team, Amount: number)
    local Players = Team:GetPlayers()
    local ChosenPlayers = {}
    for index = 1, Amount do
        local RandomIndex = math.random(1, #Players)
        table.insert(ChosenPlayers, Players[RandomIndex])
        table.remove(Players, RandomIndex)
    end
    return ChosenPlayers
end

-- Usage:
local RandomPlayers = GetPlayersFromTeam(game.Teams.In, 2)

It returns a table with the randomly selected players