Events & Connections
Code that just runs once isn't very useful for a game. We need code that reacts to players touching things, clicking buttons, or joining the game.
What is an Event?
An Event is a signal that Roblox fires when something specific happens. For example, when a Part touches another Part, it fires the .Touched event. When a player joins the server, the PlayerAdded event fires.
Connecting Functions to Events
To make your code run when an event fires, you use the :Connect() method. You pass a function inside the connect parentheses.
local lavaPart = workspace.LavaPart
-- The parameter 'hit' represents whatever part touched the lava
lavaPart.Touched:Connect(function(hit)
-- Check if the part that touched us belongs to a Player Character
local character = hit.Parent
local humanoid = character:FindFirstChild("Humanoid")
if humanoid then
humanoid.Health = 0
end
end)
Disconnecting Events
When you use :Connect(), Roblox creates a Connection object in memory. If the part is destroyed, Roblox handles the cleanup. But if the part stays in the game forever and you keep connecting new functions to it, you will create a Memory Leak.
You can manually stop listening to an event by saving the connection to a variable and calling :Disconnect().
local connection
connection = part.Touched:Connect(function(hit)
print("Touched!")
-- Disconnect immediately so it only fires ONCE
connection:Disconnect()
end)