PlayerAdded (Event): Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>JulienDethurens
STOP CAPITALIZING LINKS IN THE MIDDLE OF SENTENCES!
Better code
 
(One intermediate revision by one other user not shown)
Line 9: Line 9:
{{Example|
{{Example|
This code will print <samp>A player has entered: </samp>, followed by the player's name, everytime a player enters:
This code will print <samp>A player has entered: </samp>, followed by the player's name, everytime a player enters:
<code lua>
<syntaxhighlight lang="lua" line>
game.Players.PlayerAdded:connect(function(player)
local Players = game:GetService("Players")
 
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
print("A player has entered: " .. player.Name)
end)
end
</code>}}
 
{{EmphasisBox|'''Note''': This method does not work as expected in [[solo mode]], because the player is created before scripts that connect to PlayerAdded run.  To fix this problem during solo add this to the end of a script:|red|dark=y}}


<code lua>
Players.PlayerAdded:connect(onPlayerAdded)
for _, player in pairs(game.Players:GetChildren()) do PlayerAdded(player) end
</syntaxhighlight>}}
</code>


==See Also==
{{EmphasisBox|'''Note''': This method does not work as expected in [[Solo mode|solo mode]], because the player is created before scripts that connect to PlayerAdded run.  To fix this problem during solo add this to the end of a script:|red|dark=y}}
*[[File:Event Icon.png]][[PlayerRemoving_(Event)|PlayerRemoving]]


<syntaxhighlight lang="lua">
for _, player in ipairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
</syntaxhighlight>
== See Also ==
* [[File:Event Icon.png]][[PlayerRemoving_(Event)|PlayerRemoving]]
[[Category:Events]]
[[Category:Events]]

Latest revision as of 01:42, 18 April 2023

PlayerAdded ( Player player )
Description Fired after a player enters the game.
Member of: Players


Example

This code will print A player has entered: , followed by the player's name, everytime a player enters:

local Players = game:GetService("Players")

local function onPlayerAdded(player)
	print("A player has entered: " .. player.Name)
end

Players.PlayerAdded:connect(onPlayerAdded)


Note: This method does not work as expected in solo mode, because the player is created before scripts that connect to PlayerAdded run. To fix this problem during solo add this to the end of a script:
for _, player in ipairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end

See Also