Different ways to do this and even more possibilities you could extend to. The problem with the code you're using is that it can be reduced with using something like math.random.
Although, since you want to randomize players for two teams we could do something special with the % or modulus operator.
We first need to get the amount players in the server. Then to get half the amount we divide it by 2. We could use % to make sure it's even by looking at the remainder. If it's not even then that means the player count isn't evened out and we address it accordingly.
local Players = game:GetService("Players")
local playerArray = Players:GetPlayers()
local playerCount = #playerArray
local halfCount
if #playerCount%2 ~= 0 then
halfCount = (playerCount+1)/2
else
halfCount = playerCount/2
end
The above checks if the remainder of playerCount divided by 2 is 0. If it isn't then it means it's an odd amount of players. We add one to the count if that is the case. This means that one team will always have more than one player.
Now we could move on to setting up the teams. I will use tables as teams to organize the players.
local teamOne = Players:GetPlayers()
local teamTwo = {}
local playerCount = #teamOne
local halfCount
if playerCount%2 ~= 0 then
halfCount = (playerCount+1)/2
else
halfCount = playerCount/2
end
for i = 1, halfCount do
local rdm = math.random(1, playerCount)
local chosenPlayer = teamOne[rdm]
table.insert(teamTwo, chosenPlayer)
table.remove(teamOne, rdm)
end
In our numerical for-loop we count up to the half amount of players. We get a random player using math.random and insert them to the table. We then use table.remove to remove them from the other team table.
This system is pretty straightforward to understand and should be used when starting a new round. After this you would loop through each team table and change the player's team to the respective team in Teams service.
####Let me know if I missed anything or you want something explained more.
Edit:
Extended explanation some.
1 comment
+rep is very fancy man