Setting 1 player's team to Red, and the others to Blue

Hello!
The topic describes itself, but I’ll explain what i mean below.

  1. Get a random player from Players service, and set it to a variable (randomPlayer)
  2. Set the randomPlayer’s team to Red
  3. Set others team to Blue

Here’s the code that I have right now:

inRound.Changed:Connect(function()
	if inRound.Value == true then
		for _, players in pairs(game.Players:GetChildren()) do
			-- give a rand plr red team
			-- give others blue team
			if players > 0 then
				local randomPlayer = players[math.random(#players)]
				game.ReplicatedStorage.serverteamchanger:FireServer(randomPlayer, BrickColor.new(redcolor))
				local otherplayers = players - randomPlayer
				otherplayers.TeamColor = bluecolor
			else
				warn("no players detected")
				break
			end
		end
	else
		for _, player in pairs(game.Players:GetChildren()) do
			-- give everyone blue team
		end
	end
end)

You should change this to a server script to prevent exploiters from abusing this. So, instead, use this in a server script.

inRound.Changed:Connect(function()
	if inRound.Value == true then
		-- give a rand plr red team
		-- give others blue team
		if #players:GetPlayers() > 0 then
			local randomPlayer = players:GetPlayers()[math.random(#players:GetPlayers())]
			randomPlayer.TeamColor = BrickColor.new(redcolor)
			for i,v in pairs(players:GetPlayers()) do
				if v  ~= randomPlayer then
					v.TeamColor = BrickColor.new(bluecolor)
				end
			end
		else
			warn("no players detected")
			break
		end
	else
		for _, player in pairs(game.Players:GetPlayers()) do
			-- give everyone blue team
		end
	end
end)
1 Like

I got this error: ServerScriptService.GameRound:18: attempt to get length of a Instance value
Line 17-19:

if #players:GetPlayers() > 0 then
        local randomPlayer = players:GetPlayers()[math.random(#players)]
randomPlayer.TeamColor = BrickColor.new(redcolor)

I probably think it is the brackets: … :GetPlayers()[math.random(#players)]

ah, sorry. Here:

if #players:GetPlayers() > 0 then
    local randomPlayer = players:GetPlayers()[math.random(#players:GetPlayers()]
    randomPlayer.TeamColor = BrickColor.new(redcolor)

fixed it in the original post too

1 Like

You should use GetPlayers() instead of GetChildren() as it ensured it’s a player, not something else.

Yes, I used that everywhere else, but I didn’t edit the full script. I will change that though.

1 Like