ContextActionService

Mostrar obsoleto

*Este contenido se traduce usando la IA (Beta) y puede contener errores. Para ver esta página en inglés, haz clic en aquí.

No creable
Servicio

Permite que una experiencia vincule la entrada del usuario a acciones contextuales o acciones que solo se habilitan bajo alguna condición o período de tiempo.Por ejemplo, permitir que un jugador abra una puerta solo mientras está cerca.En el código, una acción es simplemente una cadena (el nombre de la acción) utilizada por el servicio para diferenciar entre acciones únicas.La cadena de acción se proporciona a BindAction y UnbindAction , entre otras funciones de miembros.Si dos acciones están vinculadas a la misma entrada, la más recientemente vinculada tendrá prioridad.Cuando la acción más reciente se desvincula, la que estaba vinculada antes toma el control nuevamente.Dado que este servicio trata con la entrada del usuario, solo puedes usarlo en el lado del cliente LocalScripts.

Contexto y acción

Un contexto es simplemente una condición durante la cual un jugador puede realizar alguna acción .Algunos ejemplos incluyen sostener un Tool , estar seated en un automóvil o estar cerca de una puerta.Sea cual sea el caso, depende de tu LocalScripts llamar BindAction cuando el contexto se ingrese y UnbindAction cuando el contexto se deje.

Una acción es simplemente alguna entrada que puede ser realizada por el jugador mientras está en ese contexto .Tal acción podría abrir/cerrar algún menú, activar una acción de herramienta secundaria o enviar una solicitud al servidor usando RemoteFunction:InvokeServer() .Una acción se identifica por una cadena única como el primer parámetro de ambos BindAction y UnbindAction .La cadena puede ser cualquier cosa, pero debe reflejar la acción que se está realizando, no la entrada que se está utilizando .Por ejemplo, no use "KeyH" como nombre de acción - use "CarHorn" en su lugar.Es mejor definir tus acciones como una constante en la parte superior de tu script ya que las usarás en al menos tres lugares diferentes de tu código.

Vincular acciones contextualmente

Es mejor usar el BindAction que UserInputService.InputBegan para la mayoría de los casos.Para UserInputService.InputBegan , tu función conectada tendría que verificar si el jugador está en el contexto de la acción que se está realizando.En la mayoría de los casos, esto es más difícil que simplemente llamar a una función cuando se ingresa o se deja un contexto.Por ejemplo, si quieres que la tecla H active el sonido de la bocina del coche mientras el jugador está sentado en ella, el jugador podría escribir "hola" en el chat o usar la tecla H para algo más.Es más difícil determinar si algo más está usando la tecla H (como el chat) - el coche podría sonar cuando el jugador no quería.Si en cambio usa BindAction y UnbindAction cuando el jugador ingresa/sale del automóvil, ContextActionService se asegurará de que las teclas H presionen la acción de honk solo cuando sea la acción más recientemente vinculada.Si algo más (como el chat) toma el control, no tendrás que preocuparte por verificar eso.

Inspeccionando acciones vinculadas

Para ver una lista de acciones y sus entradas vinculadas, puedes inspeccionar la pestaña "Vinculaciones de acciones" en la consola del desarrollador (F9 mientras estás en el juego).Esto muestra todas las vinculaciones, incluidas las vinculadas por scripts del núcleo de Roblox y scripts de cámara/control predeterminados también.Esto es útil para depurar si tus acciones se están vinculando/desvinculando en el momento correcto o si alguna otra acción está robando la entrada de tus acciones.Por ejemplo, si estás intentando vincular WASD , puede ser el caso de que los scripts de movimiento predeterminados se vinculan sobre esas mismas teclas.Del mismo modo, el script de control de la cámara puede robar la entrada de clic derecho si el script se ejecuta después del tuyo.

Entrada sin teclado

Este servicio es especialmente útil para soportar la entrada de gamepad y táctil.Para la entrada del gamepad, puedes elegir vincular el botón B a una acción que devuelve al usuario al menú anterior cuando ingresa a otro menú.Para el tacto, los botones táctiles en la pantalla se pueden utilizar en lugar de presionar las teclas: estos botones se muestran solo mientras la acción está vinculada, y la posición, el texto y/o las imágenes de estos botones se pueden configurar a través de este servicio.Están algo limitados en la cantidad de personalización proporcionada por este servicio; por lo general, es una mejor idea hacer tus propios botones en la pantalla usando ImageButton o TextButton.

Muestras de código

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.

ContextActionService Tool Reload

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)

Resumen

Métodos

Eventos

Propiedades

Métodos

BindAction

()

Vincule una acción a la entrada del usuario dada una función de manejo de acciones.Una vez que se realice una entrada coincidente, se llamará la función del manejador de acciones con los argumentos enumerados a continuación.Los elementos de enumeración de entrada válidos incluyen los siguiendo: Enum.KeyCode, Enum.UserInputType o Enum.PlayerActions .Llama a esta función cuando un jugador entra en el contexto en el que se puede realizar una acción.Cuando el jugador abandona el contexto, llama UnbindAction con el mismo actionName.Puedes llamar manualmente la función de manejo de acciones de una acción usando CallFunction.

El ejemplo de código a continuación muestra cómo un Sound puede ser played mientras se presiona una tecla ( H ), botón del controlador de juegos o botón de pantalla táctil.


local ContextActionService = game:GetService("ContextActionService")
-- Un sonido de bocina de coche
local honkSound = Instance.new("Sound", workspace)
honkSound.Looped = true
honkSound.SoundId = "rbxassetid://9120386436"
local function handleAction(actionName, inputState, inputObject)
if actionName == "HonkHorn" then
if inputState == Enum.UserInputState.Begin then
honkSound:Play()
else
honkSound:Pause()
end
end
end
-- Cuando el jugador se sienta en el vehículo:
ContextActionService:BindAction("HonkHorn", handleAction, true, Enum.KeyCode.H, Enum.KeyCode.ButtonY)
-- Cuando el jugador sale:
ContextActionService:UnbindAction("HonkHorn")

Parámetros del manipulador de acciones

Las funciones del manipulador de acciones se llaman con los siguientes parámetros:


<th>Tipo</th>
<th>Descripción</th>
</tr>
<tr>
<td>1</td>
<td><code>cadena</code></td>
<td>La misma cadena que se pasó originalmente a BindAction†</td>
</tr>
<tr>
<td>2</td>
<td><code>Enum.UserInputState</code></td>
<td>El estado de la entrada (Comenzar, Cambiar, Finalizar o Cancelar)*</td>
</tr>
<tr>
<td>3</td>
<td><code>Objeto de entrada</code></td>
<td>Un objeto que contiene información sobre la entrada (varía según el tipo de entrada de usuario)</td>
</tr>
#

† Esto permite que una función gestione múltiples acciones a la vez, si es necesario.:*Se envía cancelar si alguna entrada estaba en progreso y otra acción se vinculó a la entrada en progreso, o si la acción de enlace en progreso era unbound.

Pila de atajos de acción

Las vinculaciones de acción se comportan como una pila: si dos acciones están vinculadas a la misma entrada de usuario, se usará el manejador de acción más recientemente vinculado .Si un manipulador de acciones devuelve Enum.ContextActionResult.Pass , se llamará al siguiente manipulador de acciones más recientemente vinculado, y así hasta que un manipulador drene la entrada (devolviendo nil o Enum.ContextActionResult.Sink ).Cuando se llama UnbindAction, el manipulador de acciones se elimina de la pila.Este comportamiento de pila se puede anular usando BindActionAtPriority , donde un parámetro de prioridad adicional después de createTouchButton puede anular el orden en que se vinculan las acciones (mayor antes de menor).

Botones táctiles

Además de los tipos de entrada, el tercer parámetro de esta función controla si se crea un botón para dispositivos TouchEnabled .Al creacionesel primer botón de toque, se agrega un ScreenGui llamado "ContextActionGui" al PlayerGui.Dentro del ScreenGui se agrega un Frame llamado "ContextButtonFrame" que se llama.Es en este marco en el que ImageButtons para acciones vinculadas son padres; puedes usar GetButton para recuperar tales botones para la personalización.

Parámetros

actionName: string

Una cadena que representa la acción que se está realizando (por ejemplo, "HonkHorn" o "OpenDoor").

Valor predeterminado: ""
functionToBind: function

La función de manejo de acciones, llamada con los siguientes parámetros cuando se activan los inputs vinculados: string (actionName), Enum.UserInputState y un objeto de entrada.

Valor predeterminado: ""
createTouchButton: boolean

Si se debe crear un botón GUI para la acción en dispositivos de entrada táctil.

Valor predeterminado: ""
inputTypes: Tuple

Cualquier número de Enum.KeyCode o Enum.UserInputType que represente las entradas para vincular con la acción.

Valor predeterminado: ""

Devuelve

()

Muestras de código

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.

ContextActionService Tool Reload

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)

This code sample uses ContextActionService to bind an action named "BoundAction" to a general action handler function on the F key. Place this in a LocalScript inside StarterPlayerScripts and press F to see the message "Handling action: BoundAction".

General Action Handler

local ContextActionService = game:GetService("ContextActionService")
local function handleAction(actionName, inputState, inputObj)
if inputState == Enum.UserInputState.Begin then
print("Handling action: " .. actionName)
print(inputObj.UserInputType)
end
-- Since this function does not return anything, this handler will
-- "sink" the input and no other action handlers will be called after
-- this one.
end
ContextActionService:BindAction("BoundAction", handleAction, false, Enum.KeyCode.F)

This code sample demonstrates how BindAction acts like a stack. It binds two actions, FirstAction (Z, X, and C keys) and SecondAction (Z and X keys) to two action handling functions. The second one will pass on a certain input (the X key).

Both actions use the Z and X keys, however the second handler will pass input only if X is pressed. So, when X is pressed, the second handler is called and then the first. The first action is also bound to the C key, and can be triggered even though the other two inputs are "covered" by the second action.

Test this code out by pasting it into a LocalScript within StarterPlayerScripts, then pressing Z, X and C. Observe which action handlers are called with what actions.

Stacked Action Handlers

local ContextActionService = game:GetService("ContextActionService")
-- Define an action handler for FirstAction
local function actionHandlerOne(actionName, inputState, _inputObj)
if inputState == Enum.UserInputState.Begin then
print("Action Handler One: " .. actionName)
end
-- This action handler returns nil, so it is assumed that
-- it properly handles the action.
end
-- Binding the action FirstAction (it's on the bottom of the stack)
ContextActionService:BindAction("FirstAction", actionHandlerOne, false, Enum.KeyCode.Z, Enum.KeyCode.X, Enum.KeyCode.C)
-- Define an action handler for SecondAction
local function actionHandlerTwo(actionName, inputState, inputObj)
if inputState == Enum.UserInputState.Begin then
print("Action Handler Two: " .. actionName)
end
if inputObj.KeyCode == Enum.KeyCode.X then
return Enum.ContextActionResult.Pass
else
-- Returning nil implicitly Sinks inputs
return Enum.ContextActionResult.Sink
end
end
-- Binding SecondAction over the first action (since it bound more recently, it is on the top of the stack)
-- Note that SecondAction uses the same keys as
ContextActionService:BindAction("SecondAction", actionHandlerTwo, false, Enum.KeyCode.Z, Enum.KeyCode.X)

BindActionAtPriority

()

BindActionAtPriority se comporta como BindAction pero también permite asignar una prioridad a la acción vinculada.Si varias acciones están vinculadas a la misma entrada, se llama la función de prioridad más alta independientemente de la orden en que se vincularon las acciones.En otras palabras, esta función anula el comportamiento normal de "pila" de BindAction.

Parámetros

actionName: string

Una cadena que representa la acción que se está realizando (por ejemplo, "HonkHorn" o "OpenDoor").

Valor predeterminado: ""
functionToBind: function

La función de manejo de acciones, llamada con los siguientes parámetros cuando se activan los inputs vinculados: string (actionName), Enum.UserInputState y un objeto de entrada.

Valor predeterminado: ""
createTouchButton: boolean

Si se debe crear un botón GUI para la acción en dispositivos de entrada táctil.

Valor predeterminado: ""
priorityLevel: number

El nivel de prioridad en el que debe vincularse la acción (se considera más alto antes de más bajo).

Valor predeterminado: ""
inputTypes: Tuple

Cualquier número de Enum.KeyCode o Enum.UserInputType que represente los inputs para vincular con la acción.

Valor predeterminado: ""

Devuelve

()

Muestras de código

This code sample demonstrates how ContextActionService:BindActionAtPriority() can be used to bind actions out of order yet still have the same priority levels. Normally, BindAction() would operate on order (last bound action has highest priority), but priority levels override this. You can test this code by pasting it into a Script with RunContext = Client in ReplicatedStorage.

ContextActionService BindAction Priorities

local ContextActionService = game:GetService("ContextActionService")
local INPUT_KEY1 = Enum.KeyCode.Q
local INPUT_KEY2 = Enum.KeyCode.E
local function handleThrow(actionName: string, inputState: Enum.UserInputState, inputObject: InputObject)
if inputState ~= Enum.UserInputState.Begin then
return Enum.ContextActionResult.Pass
end
print(`Action [{actionName}] occurred. KeyCode [{inputObject.KeyCode}] pressed.`)
return Enum.ContextActionResult.Sink
end
local function handlePunch(actionName: string, inputState: Enum.UserInputState, inputObject: InputObject)
if inputState ~= Enum.UserInputState.Begin then
return Enum.ContextActionResult.Pass
end
print(`Action [{actionName}] occurred. KeyCode [{inputObject.KeyCode}] pressed.`)
return Enum.ContextActionResult.Sink
end
-- Without specifying priority, the most recently bound action is called first,
-- so pressing INPUT_KEY1 prints "Punch" and then sinks the input.
ContextActionService:BindAction("DefaultThrow", handleThrow, false, INPUT_KEY1)
ContextActionService:BindAction("DefaultPunch", handlePunch, false, INPUT_KEY1)
-- Here we bind both functions in the same order as above, but with explicitly swapped priorities.
-- That is, we give "Throw" a higher priority of 2 so it will be called first,
-- despite "Punch" still being bound more recently.
-- Pressing INPUT_KEY2 prints "Throw" and then sinks the input.
ContextActionService:BindActionAtPriority("PriorityThrow", handleThrow, false, 2, INPUT_KEY2)
ContextActionService:BindActionAtPriority("PriorityPunch", handlePunch, false, 1, INPUT_KEY2)

BindActivate

()

Vincula un Enum.KeyCode que se puede usar con un Enum.UserInputType para activar eventos ClickDetector , Tools y GuiButtons .Cuando se presiona la clave/botón dada, se activa el evento Mouse.Button1Down en el ratón enviado a Tool.Equipped .Esto a su vez activa el evento Tool.Activated si Tool.ManualActivationOnly no está configurado como verdadero.Para la entrada del gamepad, esta función es llamada por los scripts de control predeterminados con el fin de vincular el botón R2 Enum.KeyCode .

Tenga en cuenta que el Enum.UserInputType especificado debe ser Keyboard o Gamepad1 a través de Gamepad8 para ser válido.

Parámetros

userInputTypeForActivation: Enum.UserInputType

Debe ser Teclado o Gamepad1 a través de Gamepad8.

Valor predeterminado: ""
keyCodesForActivation: Tuple
Valor predeterminado: ""

Devuelve

()

GetAllBoundActionInfo

GetAllBoundActioninfo devuelve una tabla que mapea todos los nombres de acciones (aquellos que originalmente se pasaron a BindAction ) a una tabla devuelta por GetBoundActionInfo cuando se llama con el nombre de acción en sí.Al usar esta función, puedes inspeccionar todas las acciones actualmente vinculadas.Esto es útil al depurar sus niveles de prioridad o órdenes de pila.


Devuelve

GetBoundActionInfo

GetBoundActionInfo devuelve una tabla con las siguientes claves que describen una acción vinculada dada su nombre.Para obtener la misma información para todas las acciones a la vez, use GetAllBoundActionInfo .


<th>Tipo</th>
<th>Descripción</th>
</tr>
<tr>
<td><code>orden de pila</code></td><td>número</td>
<td>
Describe el índice de la acción en la pila (aumentando)
</td>
</tr>
<tr>
<td><code>nivel de prioridad</code> \*</td><td>número</td>
<td>
Describe el nivel <code>Class.ContextActionService:BindActionAtPriority()|priority</code> de la acción
</td>
</tr>
<tr>
<td><code>crear botón de toque</code></td><td>bool</td>
<td>
Describe si debe crearse un botón táctil en <code>Class.UserInputService.TouchEnabled|TouchEnabled</code> dispositivos
</td>
</tr>
<tr>
<td><code>tipos de entrada</code></td><td>tabla</td>
<td>
Los tipos de entrada pasados a <code>Class.ContextActionService:BindAction()|BindAction</code> para los cuales se desencadenadoresta acción
</td>
</tr>
<tr>
<td><code>descripción</code> †</td><td>cadena</td>
<td>
La descripción de la acción establecida por <code>Class.ContextActionService:SetDescription()|SetDescription</code>
</td>
</tr>
<tr>
<td><code>título</code> †</td><td>cadena</td>
<td>
El título del conjunto de acciones establecido por <code>Class.ContextActionService:SetTitle()|SetTitle</code>
</td>
</tr>
<tr>
<td><code>imagen</code> †</td><td>cadena</td>
<td>
La imagen del botón de toque de la acción establecido por <code>Class.ContextActionService:SetImage()|SetImage</code>
</td>
</tr>
Nombre

:* El nivel de prioridad seguirá incluyéndose incluso si BindActionAtPriority no se usó - por defecto será 2000.

† Indica que este campo será nil si el método asociado no se llamó para la acción dada.

Parámetros

actionName: string
Valor predeterminado: ""

Devuelve

GetCurrentLocalToolIcon

GetCurrentLocalToolIcon devolverá el BackpackItem.TextureId de un Tool actualmente equipped por el Player , o nil si no hay tal herramienta o si el jugador carece de una Character .


Devuelve

Una cadena de contenido del ID de textura del herramienta, o nil si no se pudo encontrar uno.

SetDescription

()

SetDescription establecerá la descripción de una acción vinculada por BindAction.En una lista de acciones disponibles, este sería el texto que describe la acción dada.

Aunque el nombre pueda sugerir que este método está relacionado con la familia de funciones que personalizan un botón táctil para acciones que los crean (SetTitle, SetImage y SetPosition), este método no afecta a tal botón.Este método simplemente establece una descripción de texto de una acción, y nada más.

Parámetros

actionName: string

El nombre de la acción originalmente pasada a BindAction.

Valor predeterminado: ""
description: string

Una descripción de texto de la acción, como "Tocar la bocina del coche" o "Abrir el inventario".

Valor predeterminado: ""

Devuelve

()

Muestras de código

This code sample demonstrates binding an "Inspect" action to a touch button created automatically by ContextActionService. The button is customized using SetImage(), SetTitle(), SetDescription() and SetPosition(). The button is further customized by using GetButton() to get a reference to the ImageButton itself and tinting it green by setting ImageButton.ImageColor3.

Paste this code into a LocalScript placed within StarterPlayerScripts to test it. In Studio, be sure to toggle the touch device emulator in order for the button to actually be created.

ContextActionService Touch Button

local ContextActionService = game:GetService("ContextActionService")
local ACTION_INSPECT = "Inspect"
local INPUT_INSPECT = Enum.KeyCode.E
local IMAGE_INSPECT = "rbxassetid://1826746856" -- Image of a speech bubble with ? in it
local function handleAction(actionName, inputState, _inputObject)
if actionName == ACTION_INSPECT and inputState == Enum.UserInputState.End then
print("Inspecting")
end
end
-- For touch devices, a button is created on-screen automatically via the 3rd parameter
ContextActionService:BindAction(ACTION_INSPECT, handleAction, true, INPUT_INSPECT)
-- We can use these functions to customize the button:
ContextActionService:SetImage(ACTION_INSPECT, IMAGE_INSPECT)
ContextActionService:SetTitle(ACTION_INSPECT, "Look")
ContextActionService:SetDescription(ACTION_INSPECT, "Inspect something.")
ContextActionService:SetPosition(ACTION_INSPECT, UDim2.new(0, 0, 0, 0))
-- We can manipulate the button directly using ContextActionService:GetButton
local imgButton = ContextActionService:GetButton(ACTION_INSPECT)
if imgButton then -- Remember: non-touch devices won't return anything!
imgButton.ImageColor3 = Color3.new(0.5, 1, 0.5) -- Tint the ImageButton green
end

SetImage

()

Este método establece la imagen que se muestra en un botón táctil creado por BindAction().En particular, establece la propiedad ImageLabel.Image de la ImageLabel dentro del ImageButton que se devolvería por GetButton .Si no existe tal acción vinculada (por ejemplo,nada se devuelve por GetButton), esta función no hace nada y no lanza ningún error.

Esta función es parte de una familia de métodos que personalizan el botón táctil de una acción. Otros en esta familia incluyen SetPosition y SetTitle .

Parámetros

actionName: string

El nombre de la acción originalmente pasada a BindAction.

Valor predeterminado: ""
image: string

El valor al que debe establecerse la propiedad de imagen.

Valor predeterminado: ""

Devuelve

()

Muestras de código

This code sample demonstrates binding an "Inspect" action to a touch button created automatically by ContextActionService. The button is customized using SetImage(), SetTitle(), SetDescription() and SetPosition(). The button is further customized by using GetButton() to get a reference to the ImageButton itself and tinting it green by setting ImageButton.ImageColor3.

Paste this code into a LocalScript placed within StarterPlayerScripts to test it. In Studio, be sure to toggle the touch device emulator in order for the button to actually be created.

ContextActionService Touch Button

local ContextActionService = game:GetService("ContextActionService")
local ACTION_INSPECT = "Inspect"
local INPUT_INSPECT = Enum.KeyCode.E
local IMAGE_INSPECT = "rbxassetid://1826746856" -- Image of a speech bubble with ? in it
local function handleAction(actionName, inputState, _inputObject)
if actionName == ACTION_INSPECT and inputState == Enum.UserInputState.End then
print("Inspecting")
end
end
-- For touch devices, a button is created on-screen automatically via the 3rd parameter
ContextActionService:BindAction(ACTION_INSPECT, handleAction, true, INPUT_INSPECT)
-- We can use these functions to customize the button:
ContextActionService:SetImage(ACTION_INSPECT, IMAGE_INSPECT)
ContextActionService:SetTitle(ACTION_INSPECT, "Look")
ContextActionService:SetDescription(ACTION_INSPECT, "Inspect something.")
ContextActionService:SetPosition(ACTION_INSPECT, UDim2.new(0, 0, 0, 0))
-- We can manipulate the button directly using ContextActionService:GetButton
local imgButton = ContextActionService:GetButton(ACTION_INSPECT)
if imgButton then -- Remember: non-touch devices won't return anything!
imgButton.ImageColor3 = Color3.new(0.5, 1, 0.5) -- Tint the ImageButton green
end

SetPosition

()

Este método establece la posición de un botón táctil creado por BindAction() .En particular, establece la propiedad GuiObject.Position de la ImageButton que se devolvería por GetButton .Si no existe tal acción vinculada (por ejemplo,nada se devuelve por GetButton), esta función no hace nada y no lanza ningún error.

Esta función es parte de una familia de métodos que personalizan el botón táctil de una acción. Otros en esta familia incluyen SetImage y SetTitle .

Parámetros

actionName: string

El nombre de la acción originalmente pasada a BindAction.

Valor predeterminado: ""
position: UDim2

La posición dentro del marco de botón contextual.

Valor predeterminado: ""

Devuelve

()

Muestras de código

This code sample demonstrates binding an "Inspect" action to a touch button created automatically by ContextActionService. The button is customized using SetImage(), SetTitle(), SetDescription() and SetPosition(). The button is further customized by using GetButton() to get a reference to the ImageButton itself and tinting it green by setting ImageButton.ImageColor3.

Paste this code into a LocalScript placed within StarterPlayerScripts to test it. In Studio, be sure to toggle the touch device emulator in order for the button to actually be created.

ContextActionService Touch Button

local ContextActionService = game:GetService("ContextActionService")
local ACTION_INSPECT = "Inspect"
local INPUT_INSPECT = Enum.KeyCode.E
local IMAGE_INSPECT = "rbxassetid://1826746856" -- Image of a speech bubble with ? in it
local function handleAction(actionName, inputState, _inputObject)
if actionName == ACTION_INSPECT and inputState == Enum.UserInputState.End then
print("Inspecting")
end
end
-- For touch devices, a button is created on-screen automatically via the 3rd parameter
ContextActionService:BindAction(ACTION_INSPECT, handleAction, true, INPUT_INSPECT)
-- We can use these functions to customize the button:
ContextActionService:SetImage(ACTION_INSPECT, IMAGE_INSPECT)
ContextActionService:SetTitle(ACTION_INSPECT, "Look")
ContextActionService:SetDescription(ACTION_INSPECT, "Inspect something.")
ContextActionService:SetPosition(ACTION_INSPECT, UDim2.new(0, 0, 0, 0))
-- We can manipulate the button directly using ContextActionService:GetButton
local imgButton = ContextActionService:GetButton(ACTION_INSPECT)
if imgButton then -- Remember: non-touch devices won't return anything!
imgButton.ImageColor3 = Color3.new(0.5, 1, 0.5) -- Tint the ImageButton green
end

SetTitle

()

SetTitle establecerá el texto que se muestra en un botón táctil creado por BindAction.Específicamente, esto establece la propiedad TextLabel.Text de un TextLabel dentro del ImageButton que se devolvería por GetButton .Si no existe tal acción vinculada (por ejemplo,nada se devuelve por GetButton), esta función no hace nada y no lanza ningún error.

Esta función es parte de una familia de métodos que personalizan el botón táctil de una acción. Otros en esta familia incluyen SetImage y SetPosition .

Parámetros

actionName: string

El nombre de la acción originalmente pasada a BindAction.

Valor predeterminado: ""
title: string

El texto para mostrar en el botón.

Valor predeterminado: ""

Devuelve

()

Muestras de código

This code sample demonstrates binding an "Inspect" action to a touch button created automatically by ContextActionService. The button is customized using SetImage(), SetTitle(), SetDescription() and SetPosition(). The button is further customized by using GetButton() to get a reference to the ImageButton itself and tinting it green by setting ImageButton.ImageColor3.

Paste this code into a LocalScript placed within StarterPlayerScripts to test it. In Studio, be sure to toggle the touch device emulator in order for the button to actually be created.

ContextActionService Touch Button

local ContextActionService = game:GetService("ContextActionService")
local ACTION_INSPECT = "Inspect"
local INPUT_INSPECT = Enum.KeyCode.E
local IMAGE_INSPECT = "rbxassetid://1826746856" -- Image of a speech bubble with ? in it
local function handleAction(actionName, inputState, _inputObject)
if actionName == ACTION_INSPECT and inputState == Enum.UserInputState.End then
print("Inspecting")
end
end
-- For touch devices, a button is created on-screen automatically via the 3rd parameter
ContextActionService:BindAction(ACTION_INSPECT, handleAction, true, INPUT_INSPECT)
-- We can use these functions to customize the button:
ContextActionService:SetImage(ACTION_INSPECT, IMAGE_INSPECT)
ContextActionService:SetTitle(ACTION_INSPECT, "Look")
ContextActionService:SetDescription(ACTION_INSPECT, "Inspect something.")
ContextActionService:SetPosition(ACTION_INSPECT, UDim2.new(0, 0, 0, 0))
-- We can manipulate the button directly using ContextActionService:GetButton
local imgButton = ContextActionService:GetButton(ACTION_INSPECT)
if imgButton then -- Remember: non-touch devices won't return anything!
imgButton.ImageColor3 = Color3.new(0.5, 1, 0.5) -- Tint the ImageButton green
end

UnbindAction

()

UnbindAction desvinculará una acción por nombre de las entradas del usuario para que la función de manejo de acciones ya no se llame.Llama a esta función cuando el contexto para alguna acción ya no es aplicable, como cerrar una interfaz de usuario, salir de un automóvil o unequipping de un Tool.Vea BindAction para más información sobre cómo funcionan las acciones vinculadas.

Esta función no arrojará un error si no hay tal acción vinculada con la cadena dada .Al usar GetAllBoundActionInfo o la pestaña "Acciones vinculadas" de la consola del desarrollador, puedes averiguar qué acciones están actualmente vinculadas.

Parámetros

actionName: string
Valor predeterminado: ""

Devuelve

()

Muestras de código

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.

ContextActionService Tool Reload

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)

UnbindActivate

()

DesvincularActivar desvincula un Enum.KeyCode usado con un Enum.UserInputType para activar un Tool (o un HopperBin ) usando BindActivate .Esta función esencialmente deshace la acción realizada por esa función.

Parámetros

userInputTypeForActivation: Enum.UserInputType

El mismo tipo de entrada de usuario originalmente enviado a BindActivate.

Valor predeterminado: ""
keyCodeForActivation: Enum.KeyCode

El mismo código de clave original enviado a BindActivate.

Valor predeterminado: "Unknown"

Devuelve

()

UnbindAllActions

()

Elimina todas las funciones vinculadas.No quedarán nombres de acción.Todos los botones de toque se eliminarán.Si un botón fue manipulado manualmente, no hay garantía de que se limpie.


Devuelve

()

GetButton

Proporciona

GetButton devuelve el ImageButton creado por BindAction si su tercer parámetro era verdadero y el dispositivo es TouchEnabled .El único parámetro de esta función debe coincidir exactamente con el nombre de la acción original enviada a BindAction.

Si no se vinculó tal acción o si un botón no se creó, esta función devuelve nil .

Parámetros

actionName: string

El nombre de la acción originalmente pasada a BindAction.

Valor predeterminado: ""

Devuelve

Un botón de imagen creado por BindAction.

Eventos

LocalToolEquipped

Se enciende cuando el jugador actual se equipa con un Tool.

Parámetros

toolEquipped: Instance

LocalToolUnequipped

Se enciende cuando el jugador actual desequipa un Tool .

Parámetros

toolUnequipped: Instance