In addition to properties and functions, every object also has events which can be used to set up cause-and-effect systems. Events send out signals when specific things happen in a game, such as a player touching an object or a player connecting to the game. To fire an event is to have it send out such a signal.
The Wait()
function will cause the script to pause until the event occurs once. When it does, the function returns the data associated with the event’s firing.
local myPart = game.Workspace.Part-- Wait until another part collides with "myPart"local otherPart = myPart.Touched:Wait()print("Part was touched by: " .. otherPart.Name)
The Connect()
function can be used when a given function should run every time an event fires. This function immediately returns a connection object. In the example below, we connect a function, onTouched()
, to a Part
in the Workspace
. If another part collides with myPart
, the script prints the name of the other part involved in the collision.
local myPart = game.Workspace.Partlocal function onTouched(otherPart)print("Part was touched by: " .. otherPart.Name)endmyPart.Touched:Connect(onTouched)
Eventually, you may no longer need a connected function to run when an event fires. To disconnect it, use the Disconnect()
method of the connection object returned by Connect()
.
local points = Instance.new("NumberValue")points.Name = "Points"points.Value = 0local connectionlocal function onPointsChanged(newPoints)print("Points: " .. newPoints)if newPoints >= 50 then-- Stop listening for changes if we have at least 50 pointsconnection:Disconnect()endendconnection = points.Changed:Connect(onPointsChanged)-- Trigger some changespoints.Value = 25points.Value = 100points.Value = 0 -- Prints nothing because we called Disconnect()
Almost every event in Roblox will send data relevant to the event’s occurrence. For example, when a Player
joins the game, the Players.PlayerAdded
event fires with a reference to the new player.
local Players = game:GetService("Players")local function onPlayerAdded(player)print(player.Name .. " joined the game")endPlayers.PlayerAdded:Connect(onPlayerAdded)
Sometimes you will need to connect a function to an event on an object provided by another event. To do so, define a second local function within the function connected to the first event.
A common example is detecting when a player’s character is spawned into the game. For this, you’ll need to access the CharacterAdded
event of the Player
involved in the Players.PlayerAdded
event.
local Players = game:GetService("Players")local function onPlayerAdded(player)local function onCharacterAdded(character)print(player.Name .. " spawned in: " .. character:GetFullName())endplayer.CharacterAdded:Connect(onCharacterAdded)endPlayers.PlayerAdded:Connect(onPlayerAdded)