I have seen in a lot of scripts that shows "connect". What does it do? Where is it used?
COMMUNITY QUESTION
What is connect?
1 answer
connect is a method of ROBLOX Events. Methods use : instead of . before their name (use :connect not .connect)
We connect to an event (like Touched, the event on a part that fires when something touches it; or PlayerAdded the event of the Players service which fires when a new player joins). Wiki section on connecting
The connection asks for a function value which is called by the connection -- we tell it what to do when the event occurs.
As a simple example, here's a simple script utilizing connections.
-- A function which destroys whatever you give it
function DestroyPart(part)
part:Destroy();
end
script.Parent.Touched:connect( DestroyPart );
-- Connect to `script.Parent` `Touched` event (assuming it's a Part)
-- telling it that we want to destroy anything that touches it
Here is a version of that script broken down a bit more:
local DestroyPart = function(part)
part:Destroy();
end
-- `DestroyPart` is actually a VARIABLE
-- that we can pass as an argument when
-- `connect`ing
local touchEvent = script.Parent.Touched;
-- Ask to `connect` to `touchEvent`
touchEvent:connect(DestroyPart);
-- telling it to use the function that's in the variable `DestroyPart`
This discussion is preserved as it was. New answers, comments, and votes are closed.
