PcoWSkbVqDnWTu_dm2ix

5 min

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.

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.

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

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.

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 Player/CharacterAdded|CharacterAdded event of the Player involved in the Players/PlayerAdded event.

Custom Game Events Using BindableEvent

Often times, you will need to define your own events for gameplay, such as when a team scores a goal. You might have one script award that team a point and another script launch some fireworks. For this, you’ll need to use a BindableEvent which features a single user-fireable event named BindableEvent/Event|Event.

You can either use a BindableEvent that already exists in the game hierarchy or create one using Instance.new(). Then, call BindableEvent/Fire|Fire with any relevant data to trigger the BindableEvent/Event|Event. For example:

Client-Server Events

Roblox runs on a client-server model. As such, some events that fire on the server will replicate and also fire on the client. This depends on the event, but when a game needs to define a custom event to be replicated from server-to-client or vice-versa, a RemoteEvent can be used. This works similarly to BindableEvent but is network-ready. For more information, see the articles/Roblox Client Server Model|Roblox Client-Server Model article.

Tags:
  • event
  • signal