How do events work?

I kinda know how events work But something still confuse me like why do I need to use a function etc.

Hope this made sense

1 Like

The function houses the code that will be executed when the event is triggered. You have to tell the script what you want it to do when the event happens, and so to do this you put it inside of a function. This way it is seperated from the other code in your script which executes when the script runs. The event will call/run your function automatically when it is triggered.

9 Likes

Events trigger something (usually a function) when activated. For example,

game.Players.PlayerAdded:Connect(function(player)
-- code
end 

would activate whena player is added. Some events pass parameters, such as the player in .PlayerAdded.
Hope this helps.

2 Likes

Here’s how it breaks down, to the computer, in an understandable way.

An event is simply something that happens. For example, every part in Roblox has a “touched” event, which fires when they collide with another object. So, if you connect a function to the touched event of a part, as so:

local part = workspace.Part

function onTouch(touchPart)
    print(touchPart.Name)
end

part.Touched:Connect(onTouch)

What will happen is, when the part is touched, the part touching it will be printed out. This is not the only event, there are TONS of other events that can be used to do almost everything!

2 Likes