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.
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.
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
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)