PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Bind and Unbind a Function

Bind and Unbind a Function

Sep 26 2018, 11:28 AM PST

This example uses the RunService to bind and unbind a function named printHello. First, we bind the function to the RenderStep so that fires every step. Then, after we wait 5 seconds (wait(5)), we unbind the function.

Please note that we take caution to surround the function unbind in a pcall to prevent the code from breaking due to an error being thrown if the function name passed does not match the name of an already bound function. While we know that the function used in this example is bound when we try to unbind it, doing this is good coding practice.

local RunService = game:GetService("RunService")

-- Step 1: Declare the function and a name
local name = "Print Hello"
function printHello()
	print("Hello")
end

-- Step 3: Bind the function
RunService:BindToRenderStep(name, Enum.RenderPriority.First.Value, printHello)

-- Step 3: Unbind the function
local success, message = pcall(function() RunService:UnbindFromRenderStep(name) end)
if success then
	print("Success: Function unbound!")
else 
	print("An error occurred: " .. message)
end