Roblox Wiki
Advertisement
Roblox Wiki
Tutorial page
This article is an intermediate tutorial.

In this tutorial, we will use Light service iconDark service iconContextActionService to detect key/button presses for specific actions.

What is ContextActionService?[]

ContextActionService is a service that is handy for making actions occur when specific inputs happen. This service can detect a system-made button press, as well as actions, key presses, and more.

ContextActionService can ONLY be used in LocalScript light iconLocalScript dark iconLocalScripts, not Script light iconScript dark iconScripts.

Example: Toggling a GUI[]

For this tutorial, we are going to use ContextActionService to make a gui open/close. We are going to start by creating a ScreenGui light iconScreenGui dark iconScreenGui, naming it "Toggle," and putting a LocalScript inside of it.

We are going to start by defining ContextActionService, the Player, the Player's PlayerGui, and the Toggle gui.

local CAS = game:GetService("ContextActionService")
local player = game.Players.LocalPlayer
local pGui = player:WaitForChild("PlayerGui")
local t = pGui:WaitForChild("Toggle")

In order to make this gui toggle, we are going to use the gui's Enabled property, inside of a function.

local CAS = game:GetService("ContextActionService")
local player = game.Players.LocalPlayer
local pGui = player:WaitForChild("PlayerGui")
local t = pGui:WaitForChild("Toggle")

function Main()
    t.Enabled = not t.Enabled
end

Lastly, we need to use ContextActionService to bind the action. ContextActionService has a method called "BindAction" which we will use in this tutorial. Lets say we want the key "T" to toggle this gui.

local CAS = game:GetService("ContextActionService")
local player = game.Players.LocalPlayer
local pGui = player:WaitForChild("PlayerGui")
local t = pGui:WaitForChild("Toggle")

function Main()
    t.Enabled = not t.Enabled
end

CAS:BindAction("ToggleGUI",Main,true,Enum.KeyCode.T)

The 'BindAction' takes a minimum of 4 parameters, but can have any number of parameters. Lets start with the first parameter, which we used "ToggleGUI" in this scenario. The first parameter is called "actionName", and this parameter is used as a name in the system for different methods in the future. The second parameter is the function that runs when this bound action takes place. In this case, the Main function we made. The third parameter is a bool stating whether or not a button will be made on mobile devices to toggle this action. The forth parameter is a Tuple that defines what actions will trigger this bound action. In this case, we used the "T" button.

Advertisement