How do I choose a random player out of my game?

Hello everyone! My question is very simple and I’m kinda new to scripting. My question is how can I choose a random player in my game to join a team and for the rest of the players to join a different team? Thanks

1 Like

it will randomly pick a team for each player

local Teams = game.Teams:GetChildren()

for i, v in pairs(game.Players:GetChildren())
    v.Team = Teams[math.random(1, #Teams)]
end
local players = game:GetService('Players')
local randomPlayer = players:GetChildren()[math.random(1,#players:GetChildren())]

Although, you might want to use an array of select players in order to ignore players who are not ready to be picked. You might prefer to write a function like this:

function GetRandomPlayer(arrayOfPlayers)
	return arrayOfPlayers[math.random(1,#arrayOfPlayers)]
end

local setOfPlayers = game:GetService('Players'):GetChildren() -- Just an example
print(GetRandomPlayer(setOfPlayers).Name)

Here are some articles that might be relevant:

-- this code gets the teams service
-- this assumes that you already created teams for the random player and the rest of the players
local teams = game:GetService("Teams")
local team1 = teams.[Put first team name in here]
local team2 = teams.[Put second team name in here]

-- gets the players service
local players = game:GetService("Players")

-- gets a random number using the math.random function, with 1 being the minimum and the total number of players being the maximum
local randomNumber = math.random(1, #players:GetPlayers())
-- gets a random player from the players list using the randomNumber variable
local randomPlayer = players:GetPlayers()[randomNumber]

-- assigns the team1 to the randomPlayer
randomPlayer.Team = team1

-- loop that goes through every player
for index, player in pairs(players:GetPlayers()) do
	-- if the player is not the random player that was already put on a team
	if player ~= randomPlayer then
		-- assign this player the other team
		player.Team = team2
	end
end

I am assuming that you have already created the teams for your players, but to do that, go into your explorer, and there should be a “Teams” service. Right click that, then click “Insert Object…”. Select “Team” and name them. Then go into this script and replace the team names there.

If you have any more questions, feel free to ask.

1 Like

Thanks alot for the answer with a lot of effort :relaxed::+1:

1 Like

Thank you! I made an edit just after you marked it as the solution, btw.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.