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.
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)
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
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()
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.
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)