Events

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.

Waiting for an Event

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)

Connecting a Function

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.Part
local function onTouched(otherPart)
print("Part was touched by: " .. otherPart.Name)
end
myPart.Touched:Connect(onTouched)

Disconnecting a Function

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 = 0
local connection
local function onPointsChanged(newPoints)
print("Points: " .. newPoints)
if newPoints >= 50 then
-- Stop listening for changes if we have at least 50 points
connection:Disconnect()
end
end
connection = points.Changed:Connect(onPointsChanged)
-- Trigger some changes
points.Value = 25
points.Value = 100
points.Value = 0 -- Prints nothing because we called Disconnect()

Event Data

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")
end
Players.PlayerAdded:Connect(onPlayerAdded)

Nested Connections

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())
end
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)