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

How would I assign players to a new team?

What I want to do is:

  • Assign a certain percentage of players to the Red team

  • Assign a certain percentage of players to the Blue team

  • Assign the rest to the yellow team

If I can't do percentages then I would like to just manually setup it like this:

if numofplayers == 3 then

--assign one player to red

--assign one player to blue

--assign the rest to yellow

end

etc.

Any help?

2 answers

edit: I messed up the math in the percentage. Also tested the code this time, it should work. change percentage table to change the percentage of people in each team.

I did this for one of my games, I didn't test the code yet so let me know if it doesn't work assuming you have the teams as RedTeam BlueTeam YellowTeam Also this assumes there is at least 3 people in the server

Players = game:GetService("Players")

blueteam = game.Teams.BlueTeam
yellowteam = game.Teams.YellowTeam
redteam = game.Teams.RedTeam
percentage = {blue = .05,red = .05, yellow = .90} -- this has to equal 1,currently 5% of people will be in blue 5% in red 90% in yellow

function AssignTeams() -- assumes more than 3 players
	local playerlist = Players:GetPlayers() -- get players
	local totalplayers = #playerlist -- total players
	local redpercent = math.ceil(totalplayers * percentage.red) -- calculate red team
	local bluepercent = math.ceil(totalplayers * percentage.blue) -- calculate blue team
	local i = redpercent
	while i > 0 do
		playerlist[i].Team = redteam
		i = i-1
	end
	i = bluepercent
	while i>0 do
		playerlist[i+redpercent].Team = blueteam
		i = i-1
	end
	i = totalplayers - bluepercent - redpercent
	while i> 0 do
		playerlist[i+redpercent+bluepercent].Team = yellowteam
		i = i-1
	end
end

3 comments

0

I shall give it a test

0

Errors on line 9, changed it to "game.Players:GetPlayers()" but then it errors on line 20.

0

Oops I butchered my math .5+.5+.9 = 1 oops

Did some of my own scripting and fixed it myself:

local plrs = game.Players:GetPlayers()


for i, plr in pairs(plrs) do
    local p = i/#plrs
    if p < 0.4 then -- 40%
	
        plr.Team = game.Teams.RedTeam
		plr.Character.Humanoid.Health = 0
		
    elseif p < 0.4 then -- 40%
	
        plr.Team = game.Teams.BlueTeam
		plr.Character.Humanoid.Health = 0
		
    else -- 20%
	
        plr.Team = game.Teams.YellowTeam
		plr.Character.Humanoid.Health = 0
		
    end
end

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