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

ContextActionService

Show deprecated

ContextActionService

Show deprecated

ContextActionService is a game service that allows a game to bind user input to contextual actions, or actions that are only enabled under some condition or period of time. For example, allowing a player to open a door only while close by. In code, an action is simply a string (the name of the action) used by the service to differentiate between unique actions. The action string is provided to ContextActionService/BindAction|BindAction and ContextActionService/UnbindAction|UnbindAction, among other member functions. If two actions are bound to the same input, the most recently bound will take priority. When the most recent action is unbound, the one bound before that takes control again. Since ContextActionService deals with user input, you can only use it in LocalScript|LocalScripts which run on the client.

What is a context?

A context is simply a condition during which a player may perform some action. Some examples include holding a Tool, being Seat|seated in a car or standing near a door. Whatever the case may be, it is up to your LocalScript|LocalScripts to call BindAction when the context is entered and UnbindAction when the context is left.

What is an action?

An action is simply some input that can be performed by the player while in that context. Such an action could open/close some menu, trigger a secondary tool action or send a request to the server using RemoteFunction/InvokeServer. An action is identified by a unique string as the first parameter of both ContextActionService/BindAction|BindAction and ContextActionService/UnbindAction|UnbindAction. The string can be anything, but it should reflect the action being performed, not the input being used. For example, don’t use “KeyH” as an action name - use “CarHorn” instead. It is best to define your actions as a constant at the top of your script since you will use it in at least three different places in your code.

Why bind actions contextually?

It’s better to use ContextActionService’s ContextActionService/BindAction|BindAction than UserInputService/InputBegan for most cases. For InputBegan, your connected function would have to check if the player is in the context of the action begin performed. In most cases, this is harder than just calling a function when a context is entered/left. For example, if you want to have the H key trigger a car horn sound while the player is sitting in it, the player might type “hello” in chat or otherwise use the H key for something else. It is harder to determine if something else is using the H key (like chat) - the car might honk when the player didn’t mean to! If you instead use ContextActionService/BindAction|BindAction and ContextActionService/UnbindAction|UnbindAction when the player enters/leaves the car, ContextActionService will make sure that H key presses trigger the honk action only when it is the most recently bound action. If something else (like chat) takes control, you won’t have to worry about checking that.

Inspecting Bound Actions

To see a list of actions and their bound inputs, you can inspect the “Action Bindings” tab in the Developer Console (F9 while in game). This shows all bindings - including those bound by Roblox CoreScripts and default camera/control scripts too. This is useful for debugging: check if your actions are being bound/unbound at the correct times, or if some other action is stealing input from your actions. For example, if you are attempting to bind WASD, it may be the case that default character movement scripts are binding over those same keys. Similarly, the camera control script can steal right-click input if the script runs after yours.

Keyboardless Input

ContextActionService is especially useful for supporting gamepad and touch input. For gamepad input, you might choose to bind the B button to an action that returns the user to the previous menu when they entire another menu. For touch, on-screen touch buttons can be used in place of key presses: these buttons display only while the action is bound, and the position, text and/or images of these buttons can be configured through this service. They are somewhat limited in the amount of customization provided by this service; it’s usually a better idea to make your own on-screen buttons using ImageButton or TextButton.

Properties

Inherited from Instance: Show Hide

bool

Archivable

Determines if an Instance can be cloned using /Instance/Clone or saved to file.

string

ClassName

[ReadOnly] [NotReplicated]

A read-only string representing the class this Instance belongs to

int

DataCost

[ReadOnly] [NotReplicated] [Deprecated]

The cost of saving the instance using data persistence.

string

Name

A non-unique identifier of the Instance

Instance

Parent

Determines the hierarchical parent of the Instance

bool

RobloxLocked

If true, the Instance and its descendants cannot be indexed or edited by a Script or LocalScript and will throw an error if it is attempted

bool

archivable

[Hidden] [NotReplicated] [Deprecated]
string

className

[ReadOnly] [NotReplicated] [Deprecated]

Functions

void

BindAction ( string actionName , Function functionToBind , bool createTouchButton , Tuple inputTypes )

Bind user input to an action given an action handling function.

void

BindActionAtPriority ( string actionName , Function functionToBind , bool createTouchButton , int priorityLevel , Tuple inputTypes )

Behaves like ContextActionService/BindAction|BindAction but also allows a priority to be assigned to the bound action for overlapping input types (higher before lower)

void

BindActionToInputTypes ( string actionName , Function functionToBind , bool createTouchButton , Tuple inputTypes )

[Deprecated]

Binds functionToBind to input events such as key presses, mouse movement, or controller input.

void

BindActivate ( UserInputType userInputTypeForActivation , KeyCode keyCodeForActivation )

Bind a Enum/KeyCode with a specific Enum/UserInputType to trigger Tool/Activation

Dictionary

GetAllBoundActionInfo ( )

Get a table of information about all bound actions (key is the name passed to ContextActionService/BindAction|BindAction, value is a table from ContextActionService/GetBoundActionInfo|GetBoundActionInfo when called with the key)

Dictionary

GetBoundActionInfo ( string actionName )

Get a table of information about a bound action given its name originally passed to ContextActionService/BindAction|BindAction

Instance

GetButton ( string actionName )

[Yields]

Retrieves a ImageButton of a ContextActionService/BindAction|bound action that had a touch input button created.

string

GetCurrentLocalToolIcon ( )

Return the BackpackItem/TextureId of a Tool currently Tool/Equipped|equipped by the Player

void

SetDescription ( string actionName , string description )

Given the name of a bound action with a touch button, sets the description of the action.

void

SetImage ( string actionName , string image )

If actionName key contains a bound action, then image is set as the image of the touch button.

void

SetPosition ( string actionName , UDim2 position )

Given the name of a bound action with a touch button, sets the position of the button within the ContextButtonFrame.

void

SetTitle ( string actionName , string title )

Given the name of a bound action with a touch button, sets the text shown on the button.

void

UnbindAction ( string actionName )

Unbind an action from input given its name.

void

UnbindActivate ( UserInputType userInputTypeForActivation , KeyCode keyCodeForActivation )

Unbind a Enum/KeyCode with a specific Enum/UserInputType from triggering Tool/Activation when bound with ContextActionService/BindActivate

void

UnbindAllActions ( )

Removes all functions bound. No actionNames will remain. All touch buttons will be removed.

Inherited from Instance: Show Hide

void

ClearAllChildren ( )

This function destroys all of an Instance's children.

Instance

Clone ( )

Create a deep copy of a Roblox instance and descendants where Archivable = true.

void

Destroy ( )

Sets the Instance/Parent property to nil, locks the Instance/Parent property, disconnects all connections and calls Destroy on all children.

Instance

FindFirstAncestor ( string name )

Returns the first ancestor of the Instance whose Instance/Name is equal to the given name.

Instance

FindFirstAncestorOfClass ( string className )

Returns the first ancestor of the Instance whose Instance/ClassName is equal to the given className.

Instance

FindFirstAncestorWhichIsA ( string className )

Returns the first ancestor of the Instance for whom Instance/IsA returns true for the given className.

Instance

FindFirstChild ( string name , bool recursive )

Returns the first child of the Instance found with the given name.

Instance

FindFirstChildOfClass ( string className )

Returns the first child of the Instance whose Instance/ClassName|ClassName is equal to the given className.

Instance

FindFirstChildWhichIsA ( string className , bool recursive )

Returns the first child of the Instance for whom Instance/IsA returns true for the given className.

Variant

GetAttribute ( string attribute )

RBXScriptSignal

GetAttributeChangedSignal ( string attribute )

Dictionary

GetAttributes ( )

Objects

GetChildren ( )

Returns an array containing all of the Instance's children.

string

GetDebugId ( int scopeLength )

[NotBrowsable]

Returns a coded string of the Instances DebugId used internally by Roblox.

Array

GetDescendants ( )

[CustomLuaState]

Returns an array containing all of the descendants of the instance

string

GetFullName ( )

Returns a string describing the Instance's ancestry.

RBXScriptSignal

GetPropertyChangedSignal ( string property )

Get an event that fires when a given property of an object changes.

bool

IsA ( string className )

[CustomLuaState]

Returns true if an Instance's class matches or inherits from a given class

bool

IsAncestorOf ( Instance descendant )

Returns true if an Instance is an ancestor of the given descendant.

bool

IsDescendantOf ( Instance ancestor )

Returns true if an Instance is a descendant of the given ancestor.

void

Remove ( )

[Deprecated]

Sets the object’s Parent to nil, and does the same for all its descendants.

void

SetAttribute ( string attribute , Variant value )

Instance

WaitForChild ( string childName , double timeOut )

[CustomLuaState] [CanYield]

Returns the child of the Instance with the given name. If the child does not exist, it will yield the current thread until it does.

Objects

children ( )

[Deprecated]

Returns an array of the object’s children.

Instance

clone ( )

[Deprecated]
void

destroy ( )

[Deprecated]
Instance

findFirstChild ( string name , bool recursive )

[Deprecated]
Objects

getChildren ( )

[Deprecated]
bool

isA ( string className )

[Deprecated] [CustomLuaState]
bool

isDescendantOf ( Instance ancestor )

[Deprecated]
void

remove ( )

[Deprecated]

Events

RBXScriptSignal

LocalToolEquipped ( Instance toolEquipped )

Fires when the current player equips a Tool.

RBXScriptSignal

LocalToolUnequipped ( Instance toolUnequipped )

Fires when the current player unequips a Tool.

Inherited from Instance: Show Hide

RBXScriptSignal

AncestryChanged ( Instance child , Instance parent )

Fires when the Instance/Parent property of the object or one of its ancestors is changed.

RBXScriptSignal

AttributeChanged ( string attribute )

RBXScriptSignal

Changed ( string property )

Fired immediately after a property of an object changes.

RBXScriptSignal

ChildAdded ( Instance child )

Fires when an object is parented to this Instance.

RBXScriptSignal

ChildRemoved ( Instance child )

Fires when a child is removed from this Instance.

RBXScriptSignal

DescendantAdded ( Instance descendant )

Fires when a descendant is added to the Instance

RBXScriptSignal

DescendantRemoving ( Instance descendant )

Fires immediately before a descendant of the Instance is removed.

RBXScriptSignal

childAdded ( Instance child )

[Deprecated]

Code Samples


ContextActionService Tool Reload

This example properly shows how to use ContextActionService in binding user input to a contextual action. The context is the tool being equipped; the action is reloading some weapon. Test this code sample by placing it in a LocalScript parented to a Tool. When the Tool is equipped, a “Reload” action is bound, and when the Tool is unequipped the “Reload” action is unbound. When the player presses R with the Tool equipped, the message “Reloading!” will appear.

local ContextActionService = game:GetService("ContextActionService")

local ACTION_RELOAD = "Reload"

local tool = script.Parent

local function handleAction(actionName, inputState, inputObject)
	if actionName == ACTION_RELOAD and inputState == Enum.UserInputState.Begin then
		print("Reloading!")
	end
end

tool.Equipped:Connect(function ()
	ContextActionService:BindAction(ACTION_RELOAD, handleAction, true, Enum.KeyCode.R)
end)

tool.Unequipped:Connect(function ()
	ContextActionService:UnbindAction(ACTION_RELOAD)
end)