PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

AutoAssignable

Team

bool

This property determines whether Players will be automatically placed onto the Team when joining. If multiple teams have this property set to true, Roblox will attempt to even the teams out when Players are added.

When a Player joins a game they will be assigned to the Team with Team/AutoAssignable set to true that has the fewest players. If no such team is available, Player/Neutral will be set to true.

Note whilst using this property will help even out teams when players are added, it will not do anything when players are removed. For this reason developers may wish to implement their own team balancing system.


Code Samples


Simple Team Rebalance

This code sample includes a simple example of how to re-balance teams. When Team.AutoAssignable is set to true players will be added to Teams in a balanced fashion. However as Players leave the game this can lead to unbalanced teams as players are not reallocated. This code keeps track of the number of players in each team and, when players leave will check to see if the teams need re-balancing.

local Teams = game:GetService("Teams")

-- create two teams
local redTeam = Instance.new("Team", Teams)
redTeam.TeamColor = BrickColor.new("Bright red")
redTeam.AutoAssignable = true
redTeam.Name = "Red Team"

local blueTeam = Instance.new("Team", Teams)
blueTeam.TeamColor = BrickColor.new("Bright blue")
blueTeam.AutoAssignable = true
blueTeam.Name = "Blue Team"

-- start counting the number of players on each team
local numberRed, numberBlue = 0, 0

local function playerAdded(team)
	-- increase the team's count by 1
	if team == redTeam then
		numberRed = numberRed + 1 
	elseif team == blueTeam then
		numberBlue = numberBlue + 1
	end	
end

local function playerRemoved(team)
	-- decrease the team's count by 1
	if team == redTeam then
		numberRed = numberRed - 1 
	elseif team == blueTeam then
		numberBlue = numberBlue - 1
	end	

	-- check if the teams are unbalanced
	local bigTeam, smallTeam = nil, nil
	if (numberRed - numberBlue) > 2 then
		bigTeam = redTeam
		smallTeam = blueTeam
	elseif (numberBlue - numberRed) > 2 then 
		bigTeam = blueTeam
		smallTeam = redTeam
	end

	if bigTeam then	
		-- pick a random player
		local playerList = bigTeam:GetPlayers()
		local player = playerList[math.random(1, #playerList)]

		-- check the player exists
		if player then
			-- change the player's team
			player.TeamColor = smallTeam.TeamColor 
			-- respawn the player
			player:LoadCharacter()
		end
	end
end

-- listen for players being added / removed
blueTeam.PlayerAdded:Connect(function(player)
	playerAdded(blueTeam)
end)

blueTeam.PlayerRemoved:Connect(function(player)
	playerRemoved(blueTeam)
end)

redTeam.PlayerAdded:Connect(function(player)
	playerAdded(redTeam)
end)

redTeam.PlayerRemoved:Connect(function(player)
	playerRemoved(redTeam)
end)