Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Problems with team sorting in two-player servers?

So apparently when I have two players in a server and I want to make 1 of them on blue team and the other one on the red team, it does not work! However, it DOES work equally for 3, 4, 5, 6 and so on players.

I also printed the num value and it said 1, meaning that it will change one player to red in a two-player server.. However, it doesn't! If I replace num in the math.random function with 1, then it works perfectly. Any ideas what the problem is?

wait(5)

for _,v in ipairs(game.Players:GetPlayers()) do
	v.TeamColor = BrickColor.new("Bright blue")
end

for _,v in pairs(game.Players:GetPlayers()) do
	local num = math.floor(game.Players.NumPlayers/2) -- Estimate Down. On a two-player server it equals ONE.
	local plrs = game.Players:GetPlayers()
		if game.Players.NumPlayers > 1 then
			wait(5)
		local randteam = game.Players:GetChildren()[math.random(num,#plrs)] -- num = one.
		randteam.TeamColor = BrickColor.new("Bright red")
	end
end

Answer as soon as you can, thank you!

1 answer

✓ Accepted answer

First, indent your code correctly.

Second, this code has a few things in it that are obviously not quite right:

  • randteam is not a team at all, but a player
  • v on line 7 is not used. This is very troubling for a for loop
  • plrs is defined inside a for loop ... iterating over that same list of players
  • You use game.Players.NumPlayers as well as #plrs in the same place
  • You use game.Players:GetChildren(), plrs, and game.Players:GetPlayers() all in the same chunk of code
  • You wait(5) in an if in a for loop

What you want to do is select half of the players, and make those players blue.

-- <compute "blueTeam" list somehow>

-- Reset everyone to red
for _, player in pairs(game.Players:GetPlayers()) do
	player.TeamColor = BrickColor.Red()
end

-- Set half of the players to blue
for _, player in pairs(blueTeam) do
	player.TeamColor = BrickColor.Blue()
end

How do you get a list of half of the players?

Do it like picking teams in school. You have everyone line up at one side of the room, players, and pick one-at-a-time to move to the other side blueTeam:

local blueTeam = {} -- starts empty
local players = game.Players:GetPlayers()

You stop once #blueTeam >= #players:

while #blueTeam < #players do
	-- select and remove a player
	local pickedPlayer = table.remove(players, math.random(#players))

	-- add that player to the blue team
	table.insert(blueTeam, pickedPlayer)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.