Is this workflow correct for ContextActionService?

I am changing the paradigm of my logic to adopt the logic of the ContextActionService.

In the example below, if the player presses the Z key for the first time, it will perform any action, for example opening a Gui. If Z is pressed again the action will be reversed, as in the example, it would close the previous Gui. In summary: Z = On, Z = Off.

local ContextActionService = game:GetService("ContextActionService")

local function TurnOff(actionName, inputState, inputObj)
	if inputState == Enum.UserInputState.Begin then
		print("It's OFF")

local function TurnOn(actionName, inputState, inputObj)
	if inputState == Enum.UserInputState.Begin then
		print("It's ON")
		ContextActionService:BindAction("Off", TurnOff, false, Enum.KeyCode.Z)

ContextActionService:BindAction("On", TurnOn, false, Enum.KeyCode.Z)

Is this the correct approach?

2nd question

How can I adopt the above logic if I want to add a clickable button to perform the same function as the Z key?
That is, both Z and clicking a button will run the same workflow.

I never take this approach to toggles, instead I just bind a toggle function and keep track of the current state when the toggle is activated.

local state = false

local function Toggle(actionName, inputState, inputObj)
	if inputState == Enum.UserInputState.Begin then
		state = not state --True becomes False, False becomes True

ContextActionService:BindAction("Toggle", Toggle, false, Enum.KeyCode.Z)

I just take this approach to clean up the code to one function and it ensures that each time the function is triggered it does in fact toggle. This then leads into your other question, as this now has a bool showing if the toggle is turned on or off.

1 Like

Yeah that was my first format.
But I want to use the stacked actions logic proposed by BindAction and so I didn’t want to adopt this Boolean logic.