PlayerAdded (Event): Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Buckethead101
No edit summary
Better code
 
(23 intermediate revisions by 9 users not shown)
Line 1: Line 1:
{{Event|name=PlayerAdded
<onlyinclude>{{Event|name = PlayerAdded
|arguments=[[Instance]] ''Player''
|arguments = [[Player]] <var>player</var>
|description= Fired after a player enters the game.
|description = Fired after a player enters the game.
|object= [[RBX.lua.Players (Service)|Players]]
|object = Players
|}}
}}</onlyinclude>


Example:
{{clear floats}}


<pre>function onPlayerEntered(newPlayer)
{{Example|
wait(10)
This code will print <samp>A player has entered: </samp>, followed by the player's name, everytime a player enters:
newPlayer.Character.Torso.Transparency = 1
<syntaxhighlight lang="lua" line>
local Players = game:GetService("Players")
 
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
end
end


game.Players.ChildAdded:connect(onPlayerEntered)</pre>
Players.PlayerAdded:connect(onPlayerAdded)
</syntaxhighlight>}}


Or, you can make something happen when someone leaves.
{{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}}


<pre>function onPlayerLeave(Player)  
<syntaxhighlight lang="lua">
local h = Instance.new("Hint")
for _, player in ipairs(Players:GetPlayers()) do
h.Parent = game.Workspace
onPlayerAdded(player)
h.Text = "A player has left!"
end
wait(3)
</syntaxhighlight>
h:remove()
== See Also ==
game.Players.ChildRemoved:connect(onPlayerLeave)</pre>
* [[File:Event Icon.png]][[PlayerRemoving_(Event)|PlayerRemoving]]
[[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