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

Is there a way to assign half of the amount of players to a certain team?

Hi, I'm trying to find a way to divide the amount of given players in half when placing them on certain teams.

This is my code:

local player = game.Players:GetPlayers()
			[math.random(2,#game.Players:GetPlayers())]
			player.TeamColor = BrickColor.new("Bright green")

As you can see, the obvious issue is that if the game only had 2 players, they'd both be on one team. I'm not sure how to do this, so any help is greatly appreciated.

2 comments

0

Maybe try checking the amount of people on both teams and if one is higher than the other, then place them on the opposite side

0

I'm working on the script for you, I'm almost done.

1 answer

✓ Accepted answer

Hey, I have made the script for you. If you have any questions, please ask me.

--Get the Player count
local playercount = #game.Players:GetChildren()

--Calculate how many players should go on the team
--Is the number even?
if playercount % 2 == 0 then
	--number is even
	local playersselected = 0
	local toselectplayers = playercount / 2
	for i, v in pairs(game.Players:GetChildren()) do
		if playersselected < toselectplayers then
			v.Neutral = false
			v.TeamColor = BrickColor.new("Bright green")
			playersselected = playersselected + 1
		end
	end
else
	--number is odd
	local playersselected = 0
	local toselectplayers = playercount / 2 + 0.5
	for i, v in pairs(game.Players:GetChildren()) do
		if playersselected < toselectplayers then
			v.Neutral = false
			v.TeamColor = BrickColor.new("Bright green")
			playersselected = playersselected + 1
		end
	end
end

4 comments

1

Thank you, this worked.

0

Glad I could help you :D

0

Just a tip, you can do local toselectplayers = math.ceil(playercount/2) instead of local toselectplayers = playercount / 2 + 0.5, this will round the number up, math.floor() will round it down.

0

Thanks! I didn't know that!

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