First, house-keeping.
- Tab your code correctly
- Use
:GetPlayers()
instead of :GetChildren()
when you want a list of players
- You can use
math.random(high)
instead of math.random(1, high)
(this will help shorten things up later)
The trouble you'll be having is that you are using players[index] = nil
to remove a player from a list. This creates a "gap" and will cause you to miscalculate #players
and lose track of all of the others:
1 | local list = { 2 , 3 , 5 , 7 , 11 , 13 } |
Instead, you want to table.remove(players, index)
. This also conveniently returns the thing removed.
Building redPlayers
will now look like this:
1 | for i = 1 , redPlayers do |
2 | local player = table.remove(players, math.random(#players)) |
3 | table.insert(redTable, player) |
4 | if player.TeamColor ~ = BrickColor.Gray() then |
5 | table.insert(redTable, player) |
6 | player.TeamColor = BrickColor.Red() |
I am not sure why you add the player to redTable
twice... I'm guessing you just want simply this:
1 | for i = 1 , redPlayers do |
2 | local player = table.remove(players, math.random(#players)) |
3 | table.insert(redTable, player) |
4 | player.TeamColor = BrickColor.Red() |
If you only want to move players from the Gray team to Red and Blue, then players
should have been built like that in the first place.
The resulting script could look something like this:
02 | for _, player in pairs (game.Players:GetPlayers()) do |
03 | if player.TeamColor = = BrickColor.Gray() then |
04 | table.insert(players, player) |
14 | for i = 1 , redPlayers do |
15 | local player = table.remove(players, math.random(#players)) |
16 | table.insert(redTable, player) |
17 | player.TeamColor = BrickColor.Red() |
20 | for i = 1 , bluePlayers do |
21 | local player = table.remove(players, math.random(#players)) |
22 | table.insert(blueTable, player) |
23 | player.TeamColor = BrickColor.Blue() |
The last thing to be wary of is that if there are fewer players
than redPlayers + bluePlayers
, you'll get an error. Also, if there's more, not everyone will be distributed to a team.
You might want to consider something like
1 | local redPlayers = math.floor( 1 / 2 + #players * 4 / 6 ) |
2 | local bluePlayers = #players - redPlayers |
Semi-advanced
There's no such thing as "advanced" code. There is a such thing as complicated code.
Most complicated code is more complicated than it should be.
Most code can be very simple. If you compare this script to yours, which is simpler? (Which also happens to be the one that doesn't error/make mistakes?)