Auto-Assign newly joined player to the team with the least players

I’m working on a soccer (football) game right now and I need the teams to be evenly distributed.

When you first join the game, you will be assigned to the “Neutral” team, functioning as a player that has not yet loaded in. When the player presses the play button, the player should be assigned to the team with the least players in it at that moment, so the teams are even.

If the amount of players in the server are uneven, for example the newly joined player is the fifth player in the server, they will be assigned randomly, but when the 6th player joins, they will be put on, for example the blue team, because red already has 3 players and blue has 2 players.

I will explain more in the comments if needed, but I think this should be a fairly easy script.

Since you only have 2 teams, using modulo is a perfect solution for this. You keep tracking on how many players are inside your game at that moment , basically counting, and you decide which team the new player should be assigned to.

local currentTotalPlayer = 5 —lets say it 5, so the new player should be assigned to team 2

local newPlayerTeam = (currentTotalPlayer % 2) + 1

With this method, you do not have to randomly assign the team to the new player.