Roblox objects and events, lesson 23
Events and Connect
Goal: Run code when something happens.
about 6 min3 practice exercises
So far your code runs once, top to bottom. Games are different: most code should run when something happens. A player joins. A part is touched. A button is clicked.
Roblox calls these events. You connect a function to an event, and Roblox calls your function every time the event fires.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.Name .. " joined the game")
end
Players.PlayerAdded:Connect(onPlayerAdded)
Read the last line as: "when PlayerAdded fires, call onPlayerAdded". Roblox passes the event's information in as parameters. For PlayerAdded that is the player who joined.
Notice there are no brackets after onPlayerAdded in Connect. You are handing over the function itself, not calling it.
You will also see the function written in place:
Players.PlayerAdded:Connect(function(player)
print(player.Name .. " joined the game")
end)
Both forms do the same thing. The second one ends with end) because the function closes and then the brackets of Connect close.
Events replace most loops. You do not ask "has anyone joined yet?" every second. You say what should happen, once, and wait.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.