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

PlayerAdded

Fires whenever a Player is assigned to the Team. A player is considered assigned if their Player/Team property is equal to the Team and Player/Neutral is false.

This event is team specific and will only fire when a Player joints the specific Team. Any function connected to this event will be passed the Player object of the player who joined the team. For example:

Team.PlayerAdded:Connect(function(player)
	print(player.Name.." has joined the team")
end)

Parameters

Name Type Default Description

The Player that was added.


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)