How do you create custom events?
That is what I’ll be covering in this tutorial and hopefully it will help you out.
If some parts do not make sense to you, I will explain at the end.
To start off, create a script, any kind (server, local, module).
Let’s make a variable and set it to a string.
local myVariable = "Hello world!"
Our goal is to make an event that fires whenever the variable is changed.
Let’s start off with creating the event.
Insert a BindableEvent as a variable, and set its Event
property as another one.
local event = Instance.new("BindableEvent")
local Changed = event.Event
local myVariable = "Hello world!"
How does the event fire? Manually. This is obviously not the most efficient way, but it’s the easiest and events were not intended to detect variable changes anyway.
Pop in a :Fire()
statement everytime you change the variable.
local event = Instance.new("BindableEvent")
local Changed = event.Event
local myVariable = "Hello world!"
myVariable = "Hi!"
event:Fire(myVariable)
myVariable = "Hello!"
event:Fire(myVariable)
That solves the firing, but how do we receive it?
Like any other event.
Let’s print myVariable
everytime the event is called.
local event = Instance.new("BindableEvent")
local Changed = event.Event
local myVariable = "Hello world!"
Changed:Connect(function(value)
print(value)
end)
myVariable = "Hi!"
event:Fire(myVariable)
myVariable = "Hello!"
event:Fire(myVariable)
And there you have it! Your own custom event. Keep in mind that events were not intended for detecting variable changes and was only used for tutorial purposes.
Review
local event = Instance.new("BindableEvent") --Creates the event
local Changed = event.Event --Bind the Event property to make it look like a real event
local myVariable = "Hello world!" --Set the initial value
Changed:Connect(function(value) --Changed is equal to 'event.Event'
print(myVariable) --Print myVariable whenever it changes
end) --Close the event
myVariable = "Hi!" --Change the variable
event:Fire(myVariable) --Fire the event
myVariable = "Hello!" --Change the variable
event:Fire(myVariable) --Fire the event
If you still don’t understand, feel free to ask questions in the comments.