Chapter 1: Variables, values and types Chapter 2: Properties and Instances Chapter 3: Conditionals and If Statements Chapter 4: Functions and Blocks Chapter 5: Event Listeners 5.1: Events 5.2: Waiting for an Event 5.3: Connect and Disconnect
5.1: Events

From Chapter 2, we know that Instances have properties. However, Instances also have events.

Events in programming, are similar to the general definition of Events. When something happens, an event sends out a signal, such as a player clicking their mouse. All Roblox games utilize these events to detect when to do something.

5.2: Waiting for an Event

With events, we can ask our code to wait for an event to happen. For example, we can ask our code to wait for a player to click their mouse before doing something. To do this, we utilize the :Wait() function which yields our code until a specific event happens.

Before we wait for the specific event we want to wait for, we need to find the event we want. The event for detecting user input is part of the UserInputService, which can be defined using :GetService(). The specific event for detecting user input is the InputBegan event.

To wait for this event we would simply write,

local UserInputService = game:GetService("UserInputService") --define UserInputService
UserInputService.InputBegan:Wait() --wait for user input to be detected

We can refer to an event by using the "." accessor as shown above. Each event of an instance is listed on developer.roblox.com.

5.3: Connect and Disconnect

Waiting for an event is great, but what if we wanted something to happen when a specific event happened?

This is where functions, that we previously learned come in. The Connect() function can be used to connect an event with a function. This will make it so a function is called each time an event is fired. Below are two examples where connect is used to connect a function so that every time a player uses input, a print statement prints.

local UserInputService = game:GetService("UserInputService") --define UserInputService

--OPTION #1: CREATING FUNCTION INSIDE OF CONNECT
UserInputService.InputBegan:Connect(function() --we create the function inside the connect function
print("Player used input!") --Print a statement every time a player uses input
end) --parenthesis to close function declaration

--OPTION #2: USING A PREVIOUSLY CREATED FUNCTION
UserInputService.InputBegan:Connect(printStatement) --The printStatement function was created previously

To be continued...

Coming Soon