Automatic random team script for 4 teams

Hey! How would I make a script that automatically teams players equally to the team with the least players or any team if they are equal? I’ve looked around and haven’t found an answer to what I need; only solutions for 2 teams which have if statements that wouldn’t work for me.

Thanks for any help.

Bumping; haven’t received a response and judging by how simple this script would be to make, it seems my post is being disregarded for whatever reason.

1 Like
Team1 = {}
Team2 = {}

	for i, v in pairs(game.Players:GetPlayers()) do
	if #Team1 == #Team2 then
	local random = math.random(1,2)
	if random == 1 then
		table.insert(Team1, tostring(v.UserId))
	else
		table.insert(Team2, tostring(v.UserId))
		end
	elseif #Team1 >= Team2 then
		
		table.insert(Team2, tostring(v.UserId))
		
	elseif #Team1 <= Team2 then
		
		table.insert(Team1, tostring(v.UserId))
		
end
end

I asked for a script like this for four teams, not 2. :slightly_frowning_face:

Okay will send it now


1 Like
local Game = game
local Players = Game:GetService("Players")
local Teams = Game:GetService("Teams")

local function OnPlayerAdded(Player)
	local TeamsArray = Teams:GetTeams() --Fetch an array of team instances.
	table.sort(TeamsArray, function(Left, Right) return #Left:GetPlayers() < #Right:GetPlayers() end) --Sort teams array by number of players ascendingly.
	Player.Team = TeamsArray[1] --Set joining player's team to the team with the least players.
end

local function OnPlayerRemoving(Player)
	Player.Team = nil --Set leaving player's team to 'nil'.
	local TeamsArray = Teams:GetTeams() --Fetch an array of team instances.
	table.sort(TeamsArray, function(Left, Right) return #Left:GetPlayers() < #Right:GetPlayers() end) --Sort teams array by number of players ascendingly.
	TeamsArray[#TeamsArray]:GetPlayers()[1].Team = TeamsArray[1] --Move a player from the largest team to the smallest team.
end

Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(OnPlayerRemoving)

Should be compatible with any number of teams.

2 Likes

Thanks a bunch! I really appreciate it.