The code you have provided has a lot of useless waiting and looping. It also doesn't successfully randomize. Lets try to make our own that will perform much better than this.
We have to solve this problem: Randomly divide all players evenly onto two teams.
The hard part of this problem is choosing random players. There exists an algorithm that uses probability to determine if a number should be selected. For each player, the probability of being selected is (number of players needed)/(number of players left). So if there were 20 players, the first players chances of getting selected is 10/20. If it is selected the next probability is 9/19, otherwise it is 10/19. By the end you will have exactly half of the players being selected.
That may have been confusing, but hopefully the code makes it easier to follow. All that is left to do is loop through the players and set the team to either "Team1" or "Team2":
local Team1 = game.Teams["Attackers"]
local Team2 = game.Teams["Defenders"]
local players = game.Players:GetPlayers()
local numNeeded = math.floor(#players/2)
local numLeft = #players
for _, player in ipairs(players) do
local probability = numNeeded/numLeft
if probability < math.random() then
player.TeamColor = Team1
numNeeded = numNeeded - 1
else
player.TeamColor = Team2
end
numLeft = numLeft - 1
end
If you have any questions, just leave a comment below.