Automatic Team Changing

  1. What do I want to achieve?
    I am making an obby where players compete to get to the end. There are 5 teams Team Blue, Team Red, Team Green, Team Yellow, Team Orange. I want to make a system which puts the player who has joined in the team with the least members. And if there are multiple teams with the same amount of players then it should put the player in a random team with less members.

  2. What is the issue?
    I don’t know how to fix this issue as I am new to scripting.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I didn’t write any scripts about it as I am new and know very less about scripting.

I would appreciate if you guys tell me about any loops or functions to be used in the script.
Thanks for reading :slight_smile:

local players = game:GetService("Players")
local teamService = game:GetService("Teams") 
local teams = teamService:GetTeams() --Returns an array containing all the teams.

players.PlayerAdded:Connect(function(plr) --The PlayerAdded event fires every time a player joins the game.
  table.sort(teams, function(a, b) return #a:GetPlayers() < #b:GetPlayers() end) --This sorts the table we got earlier (teams) in the following way: lowest number of players --> highest number of players. 
  plr.Team = teams[1] --This changes the player's team to the team with the least number of players. 
end)
1 Like