Kahibaro
Discord Login Register

2.3.4 Connecting functions to events

Why Connecting Functions to Events Matters

In Roblox, events are signals that something has happened. A part was touched, a button was clicked, a player joined, or a timer finished. These signals by themselves do nothing. Your code reacts to them by running functions.

Connecting a function to an event is how you tell Roblox, “When this happens, run this code.” This turns your scripts from simple step by step instructions into interactive behavior that responds to the player and to the game world.

In this chapter you will focus on how to connect functions to events, how the special :Connect method works, and how to handle the values that events send into your functions.

The Core Pattern: Event:Connect(function)

Every Roblox event follows the same basic connection pattern. You have:

  1. An event object, for example Part.Touched or MouseButton1Click.
  2. The :Connect method, which attaches your function to the event.
  3. A function that will run whenever the event fires.

The simplest form looks like this:

local part = workspace.Brick
local function onTouched(otherPart)
	print("The part was touched!")
end
part.Touched:Connect(onTouched)

In this example, part.Touched is the event. :Connect attaches the function onTouched to that event. Whenever the brick is touched, Roblox calls onTouched.

You can also connect an anonymous function directly, without giving it a name:

local part = workspace.Brick
part.Touched:Connect(function(otherPart)
	print("Touched by:", otherPart.Name)
end)

Both forms are valid. Named functions are easier to reuse and disconnect. Anonymous functions are quick to write for small behaviors.

Important rule: To run a function when an event happens, always call :Connect on the event and pass the function without parentheses, like event:Connect(myFunction). If you write event:Connect(myFunction()) you will call the function immediately instead of connecting it.

How Event Arguments Reach Your Function

When an event fires, it can send values into your function. These are called arguments. The exact arguments depend on the event. For example, Touched sends the part that touched, and a button click event usually sends no extra values.

The function you connect must accept the same number of arguments in the same order that the event provides. If you do not need some of them, you can ignore them, but the parameter list should still be able to accept them.

A typical Touched connection looks like this:

local part = workspace.Brick
local function onTouched(otherPart)
	print("Contact with:", otherPart.Name)
end
part.Touched:Connect(onTouched)

Here otherPart is a parameter that receives the part that touched your brick.

If an event provides multiple values, list them in the same order:

local remote = game.ReplicatedStorage.SomeRemoteEvent
local function onRemoteFired(player, data)
	print("Remote fired by", player.Name, "with data:", data)
end
remote.OnServerEvent:Connect(onRemoteFired)

If you only care about the first value, you can skip naming the others:

remote.OnServerEvent:Connect(function(player)
	print(player.Name, "fired the remote")
end)

Roblox automatically passes the arguments. You do not call the function yourself. You only define the parameters and connect the function.

Multiple Functions on the Same Event

The same event can have many connected functions. Each time the event fires, Roblox will call all connected functions in the order they were connected. For example:

local part = workspace.Brick
local function showMessage(otherPart)
	print("The brick was touched!")
end
local function showName(otherPart)
	print("Touched by:", otherPart.Name)
end
part.Touched:Connect(showMessage)
part.Touched:Connect(showName)

When the brick is touched, both showMessage and showName run. This can be useful if different scripts need to react to the same event, for example one script gives points while another plays a sound.

Disconnecting Event Connections

Sometimes you only want your function to run for a limited time, or until a certain condition is met. In that case, you can store the connection object that :Connect returns and later disconnect it.

When you call :Connect, it gives back a RBXScriptConnection object. You can keep this in a variable.

local part = workspace.Brick
local connection
local function onTouched(otherPart)
	print("Touched once, then disconnecting")
	connection:Disconnect()
end
connection = part.Touched:Connect(onTouched)

In this example, the first touch will run onTouched, which then calls connection:Disconnect(). After this, the event will no longer trigger that function.

You can also disconnect from outside the function when some other event or condition is met:

local part = workspace.Brick
local connection = part.Touched:Connect(function(otherPart)
	print("Touch detected")
end)
wait(10)
connection:Disconnect()
print("No longer listening for touches")

After 10 seconds, the connection is removed and touches will no longer print anything.

Important rule: If you are creating many connections during gameplay, especially inside loops or frequently fired events, remember to disconnect the ones you no longer need. This helps avoid unnecessary code running and can prevent performance problems.

Using Self Contained Local Functions

Defining the function right before connecting it often keeps your code clear. A common pattern is:

  1. Find or create the object that has the event.
  2. Define a local function that will handle the event.
  3. Connect the function to the event.

For example:

local button = script.Parent
local function onClick()
	print("Button clicked")
end
button.MouseButton1Click:Connect(onClick)

This structure makes it easy to see which function belongs to which connection and helps when you come back to your script later.

Handling Events That Fire Many Times

Some events can fire very often. Touch events on a moving part, Heartbeat or Stepped events, and events inside loops can run many times per second. When connecting functions to such events, you should keep the function body short and focused.

A simple approach is to do quick checks and then call other functions to do the heavier work:

local RunService = game:GetService("RunService")
local function onHeartbeat(deltaTime)
	-- Keep this lean
	updatePlayerPositions(deltaTime)
end
RunService.Heartbeat:Connect(onHeartbeat)

You should also avoid connecting the same event many times by mistake, for example inside a loop without disconnecting previous connections. That can cause your function to run multiple times for each event fire and lead to confusing behavior.

Connecting Once With a Manual Check

Roblox does not have a built in “connect only once” method on every event, but you can simulate this behavior with a simple flag that records whether the function has already run.

For example, to respond only to the first touch:

local part = workspace.Brick
local hasRun = false
local function onTouched(otherPart)
	if hasRun then
		return
	end
	hasRun = true
	print("First touch only")
end
part.Touched:Connect(onTouched)

If you want to be strict and fully stop listening, you can combine this with a stored connection and disconnect, as you saw before.

Capturing Outside Variables in Connected Functions

When you write a function for an event, that function can use variables from outside its own body. This is called a closure. You do not need any special syntax. For example:

local part = workspace.Brick
local timesTouched = 0
local function onTouched(otherPart)
	timesTouched = timesTouched + 1
	print("Touch count:", timesTouched)
end
part.Touched:Connect(onTouched)

The function remembers and updates timesTouched each time the event fires. This is useful to keep state between event calls, for example counting touches, tracking whether something is unlocked, or storing a timer value.

Be careful to avoid using a lot of large tables or objects inside many event handlers if they never get cleaned up, because that can hold memory longer than needed.

Organizing Multiple Connections in a Script

In a script that listens to several events, your code is easier to read if you group your connections in a clear area. A common approach is:

  1. At the top, set up references to important objects.
  2. Define all the event handler functions.
  3. At the bottom, connect all events to their handlers.

For example:

local part = workspace.Brick
local button = script.Parent.Button
local function onTouched(otherPart)
	print("Brick touched")
end
local function onButtonClick()
	print("Button clicked")
end
part.Touched:Connect(onTouched)
button.MouseButton1Click:Connect(onButtonClick)

This structure separates “what happens” (the functions) from “when it happens” (the connections), which makes it easier to scan and debug your code.

Summary of the Event Connection Pattern

Connecting functions to events is the key to interactive Roblox games. The core pattern is always the same. You take an event, you call :Connect on it, and you pass a function that will run when the event fires. That function can receive arguments, can be disconnected later, and can use variables from outside to keep track of state.

Core pattern:

  1. Write or choose a function: local function handler(...) end
  2. Call event:Connect(handler) without parentheses after the function name.
  3. Use the function parameters to receive the event arguments.
  4. Optionally store the returned connection and call connection:Disconnect() when you no longer need it.

Once you are comfortable connecting functions to events, you can combine this skill with specific Roblox events such as Touched, Clicked, or others, to build the interactive systems that make your game feel alive.

Views: 24

Comments

Please login to add a comment.

Don't have an account? Register now!