ContextActionService

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile
Assistenza

Consente a un'esperienza di legare l'input dell'utente alle azioni contestuali o alle azioni che sono abilitate solo sotto una condizione o un periodo di tempo.Ad esempio, consentire a un giocatore di aprire una porta solo mentre è vicino.Nel codice, un'azione è semplicemente una stringa (il nome dell'azione) utilizzata dal servizio per distinguere tra azioni uniche.La stringa di azione viene fornita a BindAction e UnbindAction , tra le altre funzioni del membro.Se due azioni sono legate allo stesso input, la più recentemente legata avrà la priorità.Quando l'azione più recente non è legata, quella legata prima riprende il controllo.Poiché questo servizio tratta l'input dell'utente, puoi utilizzarlo solo sul lato client LocalScripts .

Contesto e azione

Un contesto è semplicemente una condizione durante la quale un giocatore può eseguire qualche azione.Alcuni esempi includono il mantenimento di un Tool , essere seated in una macchina o stare vicino a una porta.Qualunque sia il caso, spetta al tuo LocalScripts chiamare BindAction quando il contesto viene inserito e UnbindAction quando il contesto viene lasciato.

Un'azione azione è semplicemente qualche input che può essere eseguito dal giocatore mentre in quel contesto.Un'azione del genere potrebbe aprire/chiudere un menu, attivare un'azione di strumento secondario o inviare una richiesta al server utilizzando RemoteFunction:InvokeServer() .Un'azione è identificata da una stringa unica come primo parametro di entrambi BindAction e UnbindAction .La stringa può essere qualsiasi cosa, ma dovrebbe riflettere l'azione che viene eseguita, non l'input utilizzato .Ad esempio, non usare "KeyH" come nome di azione - usa invece "CarHorn".È meglio definire le tue azioni come costante in cima al tuo script poiché le userai in almeno tre luoghi diversi nel tuo codice.

Legare le azioni contestualmente

È meglio utilizzare ContextActionService's BindAction piuttosto che UserInputService.InputBegan per la maggior parte dei casi.Per UserInputService.InputBegan , la tua funzione connessa dovrebbe controllare se il giocatore è nel contesto dell'azione in esecuzione.Nella maggior parte dei casi, questo è più difficile di semplicemente chiamare una funzione quando un contesto viene inserito/lassato.Ad esempio, se vuoi che la chiave H attivi il suono del clacson dell'auto mentre il giocatore è seduto in essa, il giocatore potrebbe digitare "ciao" in chat o altrimenti usare la chiave H per qualcos'altro.È più difficile determinare se qualcos'altro stia utilizzando la chiave H (come la chat) - l'auto potrebbe suonare quando il giocatore non voleva.Se invece usi BindAction e UnbindAction quando il giocatore entra/esce dall'auto, ContextActionService farà in modo che la pressione della chiave H attivi l'azione di honk solo quando è l'azione più recentemente legata.Se qualcos'altro (come la chat) prende il controllo, non dovrai preoccuparti di controllarlo.

Ispezionare le azioni legate

Per vedere un elenco di azioni e dei loro input legati, puoi ispezionare la scheda "Action Bindings" nella Console del programmatore (F9 mentre sei nel Gioco).Questo mostra tutti i legami, inclusi quelli legati dagli script del core di Roblox e dagli script della fotocamera/controllo predefiniti anche.Questo è utile per la debugazione se le tue azioni vengono legate/diselegate ai tempi corretti o se qualche altra azione sta rubando l'input dalle tue azioni.Ad esempio, se stai tentando di legare WASD , potrebbe essere il caso che gli script di movimento del personaggio predefiniti sono legati su quelle stesse chiavi.Allo stesso modo, lo script di controllo della fotocamera può rubare l'input del clic destro se lo script viene eseguito dopo il tuo.

Input senza tastiera

Questo servizio è particolarmente utile per supportare il gamepad e l'input touch.Per l'input del gamepad, puoi scegliere di associare il pulsante B a un'azione che riporta l'utente al menu precedente quando entra in un altro menu.Per il tocco, i pulsanti di tocco sullo schermo possono essere utilizzati al posto dei tasti di pressione: questi pulsanti vengono visualizzati solo mentre l'azione è legata, e la posizione, il testo e/o le immagini di questi pulsanti possono essere configurati attraverso questo servizio.Sono un po' limitati nella quantità di personalizzazione fornita da questo servizio; di solito è una buona idea creare i tuoi pulsanti sullo schermo utilizzando ImageButton o TextButton .

Campioni di codice

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)

Sommario

Metodi

Eventi

Proprietà

Metodi

BindAction

()

Lega un'azione all'input dell'utente dando una funzione di gestione dell'azione.Dopo che è stata eseguita un'input corrispondente, la funzione del gestore delle azioni verrà chiamata con gli argomenti elencati qui sotto.Gli elementi di input validi includono quelli all'interno del Seguendo: Enum.KeyCode , Enum.UserInputType o Enum.PlayerActions .Chiama questa funzione quando un giocatore entra nel contesto in cui può essere eseguita un'azione .Quando il giocatore lascia il contesto, chiama UnbindAction con lo stesso actionName.Puoi chiamare manualmente la funzione di gestione dell'azione di un'azione utilizzando CallFunction .

L'esempio di codice seguente mostra come un Sound può essere played mentre viene premuto un tasto ( H ), un pulsante del gamepad o un pulsante dello schermo touch.


local ContextActionService = game:GetService("ContextActionService")
-- Un suono del clacson dell'auto
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
-- Quando il giocatore si siede nel veicolo:
ContextActionService:BindAction("HonkHorn", handleAction, true, Enum.KeyCode.H, Enum.KeyCode.ButtonY)
-- Quando il giocatore esce:
ContextActionService:UnbindAction("HonkHorn")

Parametri del gestore delle azioni

Le funzioni del gestore delle azioni vengono chiamate con i seguenti parametri:


<th>Tipo</th>
<th>Descrizione</th>
</tr>
<tr>
<td>1</td>
<td><code>stringa</code></td>
<td>La stessa stringa che è stata originariamente passata a BindAction†</td>
</tr>
<tr>
<td>2</td>
<td><code>Enumerazione.UserInputState</code></td>
<td>Lo stato dell'input (Inizia, Cambia, Fine o Cancella)*</td>
</tr>
<tr>
<td>3</td>
<td><code>Oggetto di input</code></td>
<td>Un oggetto che contiene informazioni sull'input (varia a seconda di UserInputType)</td>
</tr>
#

† Questo consente a una funzione di gestire più azioni contemporaneamente, se necessario.:*Annullamento viene inviato se qualche input era in corso e un'altra azione è legata all'input in corso, o se l'azione legata in corso era unbound.

Stack di vincoli d'azione

Le bindazioni d'azione si comportano come uno stack: se due azioni sono legate allo stesso input dell'utente, verrà utilizzato il gestore d'azione più recentemente legato .Se un gestore di azione restituisce Enum.ContextActionResult.Pass , il gestore di azione più recentemente legato verrà chiamato, e così via fino a quando un gestore non scarica l'input (restituendo nil o Enum.ContextActionResult.Sink ).Quando viene chiamato UnbindAction, il gestore delle azioni viene rimosso dallo stack.Questo comportamento della stack può essere sovrascritto utilizzando BindActionAtPriority , dove un parametro di priorità aggiuntivo dopo createTouchButton può sostituire l'ordine in cui le azioni sono legate (più alto prima di più basso).

Tocca i pulsanti

Oltre ai tipi di input, il terzo parametro di questa funzione controlla se viene creato un pulsante per TouchEnabled dispositivi.Dopo la Creazionidel primo pulsante di tocco, viene aggiunto un ScreenGui chiamato "ContextActionGui" al PlayerGui.All'interno di ScreenGui c'è un Frame chiamato "ContextButtonFrame" che viene aggiunto.È in questo contesto in cui ImageButtons per le azioni legate vengono genitori; puoi usare GetButton per recuperare tali pulsanti per la personalizzazione.

Parametri

actionName: string

Una stringa che rappresenta l'azione che viene eseguita (ad esempio "HonkHorn" o "OpenDoor").

Valore predefinito: ""
functionToBind: function

La funzione di gestione delle azioni, chiamata con i seguenti parametri quando gli input legati vengono attivati: string (actionName), Enum.UserInputState e un InputObject.

Valore predefinito: ""
createTouchButton: boolean

Se un pulsante GUI deve essere creato per l'azione su dispositivi di input touch.

Valore predefinito: ""
inputTypes: Tuple

Qualsiasi numero di Enum.KeyCode o Enum.UserInputType che rappresenta gli input da legare all'azione.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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 si comporta come BindAction ma consente anche di assegnare una priorità all'azione legata.Se più azioni sono legate allo stesso input, viene chiamata la funzione di priorità più alta indipendentemente dall'ordine in cui le azioni sono state legate.In altre parole, questa funzione sostituisce il normale comportamento "stack" di BindAction.

Parametri

actionName: string

Una stringa che rappresenta l'azione che viene eseguita (ad esempio "HonkHorn" o "OpenDoor").

Valore predefinito: ""
functionToBind: function

La funzione di gestione delle azioni, chiamata con i seguenti parametri quando gli input legati vengono attivati: string (actionName), Enum.UserInputState e un InputObject.

Valore predefinito: ""
createTouchButton: boolean

Se un pulsante GUI deve essere creato per l'azione su dispositivi di input touch.

Valore predefinito: ""
priorityLevel: number

Il livello di priorità a cui l'azione dovrebbe essere legata (superiore considerato prima di quello più basso).

Valore predefinito: ""
inputTypes: Tuple

Qualsiasi numero di Enum.KeyCode o Enum.UserInputType che rappresenta gli input da legare all'azione.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

()

Lega un Enum.KeyCode che può essere utilizzato con un Enum.UserInputType per attivare eventi ClickDetector , Tools e GuiButtons .Quando viene premuta la chiave/il pulsante specificato, viene eseguito l'evento Mouse.Button1Down sul mouse inviato a Tool.Equipped .Questo a sua volta attiva l'evento Tool.Activated se Tool.ManualActivationOnly non è impostato su vero.Per l'input del gamepad, questa funzione viene chiamata dagli script di controllo predefiniti per legare il pulsante R2 Enum.KeyCode .

Nota che il Enum.UserInputType specificato deve essere Keyboard o Gamepad1 attraverso Gamepad8 per essere valido.

Parametri

userInputTypeForActivation: Enum.UserInputType

Deve essere Tastiera o Gamepad1 attraverso Gamepad8.

Valore predefinito: ""
keyCodesForActivation: Tuple
Valore predefinito: ""

Restituzioni

()

GetAllBoundActionInfo

GetAllBoundActioninfo restituisce una tabella che mappa tutti i nomi delle azioni (quelli originariamente inviati a BindAction ) a una tabella restituita da GetBoundActionInfo quando viene chiamata con il nome dell'azione stesso.Usando questa funzione, puoi ispezionare tutte le azioni attualmente legate.Questo è utile durante la risoluzione dei problemi dei loro livelli di priorità o degli ordini di stack.


Restituzioni

GetBoundActionInfo

GetBoundActionInfo restituisce una tabella con le seguenti chiavi che descrivono un'azione legata dato il suo nome.Per ottenere le stesse informazioni per tutte le azioni in una volta, usa GetAllBoundActionInfo .


<th>Tipo</th>
<th>Descrizione</th>
</tr>
<tr>
<td><code>stackOrder</code></td><td>numero</td>
<td>
Descrive l'indice dell'azione sulla stack (aumento)
</td>
</tr>
<tr>
<td><code>priorityLevel</code> \*</td><td>numero</td>
<td>
Descrive il <code>Class.ContextActionService:BindActionAtPriority()|priority</code> livello dell'azione
</td>
</tr>
<tr>
<td><code>createTouchButton</code></td><td>bool</td>
<td>
Descrive se deve essere creato un pulsante touch su <code>Class.UserInputService.TouchEnabled|TouchEnabled</code> dispositivi
</td>
</tr>
<tr>
<td><code>tipi di input</code></td><td>tabella</td>
<td>
I tipi di input passati a <code>Class.ContextActionService:BindAction()|BindAction</code> per i quali questa azione si grilletto
</td>
</tr>
<tr>
<td><code>descrizione</code> †</td><td>stringa</td>
<td>
La descrizione dell'azione impostata da <code>Class.ContextActionService:SetDescription()|SetDescription</code>
</td>
</tr>
<tr>
<td><code>titolo</code> †</td><td>stringa</td>
<td>
Il titolo dell'azione impostata da <code>Class.ContextActionService:SetTitle()|SetTitle</code>
</td>
</tr>
<tr>
<td><code>immagine</code> †</td><td>stringa</td>
<td>
L'immagine del pulsante di azione impostato da <code>Class.ContextActionService:SetImage()|SetImage</code>
</td>
</tr>
Nome

:* Il livello di priorità sarà ancora incluso anche se BindActionAtPriority non è stato utilizzato - per impostazione predefinita sarà 2000.

† Indica che questo campo sarà nil se il metodo associato non è stato chiamato per l'azione indicata.

Parametri

actionName: string
Valore predefinito: ""

Restituzioni

GetCurrentLocalToolIcon

GetCurrentLocalToolIcon restituirà il BackpackItem.TextureId di un Tool attualmente equipped da parte del Player , o nil se non esiste tale Strumento o se il giocatore manca di un Character .


Restituzioni

Una stringa di contenuto dall'ID della texture del Tool, o nil se non è stato possibile trovarne uno.

SetDescription

()

SetDescription imposterà la descrizione di un'azione legata da BindAction .In un elenco di azioni disponibili, questo sarebbe il testo che descrive l'azione data.

Sebbene il nome possa suggerire che questo metodo è correlato alla famiglia di funzioni che personalizza un pulsante touch per azioni che li creano ( SetTitle , SetImage e SetPosition ), questo metodo non influisce su un tale pulsante.Questo metodo imposta semplicemente una descrizione del testo di un'azione, e niente di più.

Parametri

actionName: string

Il nome dell'azione originariamente passata a BindAction.

Valore predefinito: ""
description: string

Una descrizione del testo dell'azione, come "Honk the car's horn" o "Apri l'Inventario, reportorio".

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

()

Questo metodo imposta l'immagine visualizzata su un pulsante touch creato da BindAction() .In particolare, imposta la proprietà ImageLabel.Image della ImageLabel all'interno del ImageButton che verrebbe restituito da GetButton .Se non esiste alcuna azione legata (ad esempionulla viene restituito da GetButton), questa funzione non fa nulla e non lancia alcun errore.

Questa funzione fa parte di una famiglia di metodi che personalizzano il pulsante di tocco di un'azione. Altri in questa famiglia includono SetPosition e SetTitle .

Parametri

actionName: string

Il nome dell'azione originariamente passata a BindAction.

Valore predefinito: ""
image: string

Il valore a cui la proprietà Immagine dovrebbe essere Impostare.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

()

Questo metodo imposta la posizione di un pulsante touch creato da BindAction() .In particolare, imposta la proprietà GuiObject.Position della ImageButton che verrebbe restituita da GetButton .Se non esiste alcuna azione legata (ad esempionulla viene restituito da GetButton), questa funzione non fa nulla e non lancia alcun errore.

Questa funzione fa parte di una famiglia di metodi che personalizzano il pulsante di tocco di un'azione. Altri in questa famiglia includono SetImage e SetTitle .

Parametri

actionName: string

Il nome dell'azione originariamente passata a BindAction.

Valore predefinito: ""
position: UDim2

La posizione all'interno del ContextButtonFrame.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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 imposterà il testo visualizzato su un pulsante touch creato da BindAction .In particolare, questo imposta la proprietà TextLabel.Text di un TextLabel all'interno del ImageButton che verrebbe restituito da GetButton .Se non esiste alcuna azione legata (ad esempionulla viene restituito da GetButton), questa funzione non fa nulla e non lancia alcun errore.

Questa funzione fa parte di una famiglia di metodi che personalizzano il pulsante di tocco di un'azione. Altri in questa famiglia includono SetImage e SetPosition .

Parametri

actionName: string

Il nome dell'azione originariamente passata a BindAction.

Valore predefinito: ""
title: string

Il testo da mostrare sul pulsante.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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 dislega un'azione per nome dagli input dell'utente in modo che la funzione del gestore dell'azione non verrà più chiamata.Chiama questa funzione quando il contesto per qualche azione non è più Applicabile, come chiudere un'interfaccia utente, uscire da un'auto o unequipping da un'interfaccia Tool.Vedi BindAction per ulteriori informazioni su come funzionano le azioni legate.

Questa funzione non lancerà un errore se non c'è alcuna azione legata con la Stringadata.Usando GetAllBoundActionInfo o la scheda "Action Bindings" della Console per sviluppatori, puoi scoprire quali azioni sono attualmente legate.

Parametri

actionName: string
Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

()

UnbindActivate dislega un Enum.KeyCode utilizzato con un Enum.UserInputType per attivare un Tool (o un HopperBin ) utilizzando BindActivate .Questa funzione annulla essenzialmente l'azione eseguita da quella funzione.

Parametri

userInputTypeForActivation: Enum.UserInputType

Lo stesso UserInputType originariamente inviato a BindActivate.

Valore predefinito: ""
keyCodeForActivation: Enum.KeyCode

Lo stesso KeyCode originariamente inviato a BindActivate.

Valore predefinito: "Unknown"

Restituzioni

()

UnbindAllActions

()

Rimuove tutte le funzioni legate.Non rimarranno nomi d'azione.Tutti i pulsanti di tocco verranno rimossi.Se un pulsante viene manipolato manualmente non c'è alcuna garanzia che verrà pulito.


Restituzioni

()

GetButton

Resa

GetButton restituisce il ImageButton creato da BindAction se il suo terzo parametro era vero e il dispositivo era TouchEnabled .L'unico parametro di questa funzione deve corrispondere esattamente al nome dell'azione originariamente inviata a BindAction.

Se nessuna tale azione è stata associata o se un pulsante non è stato creato, questa funzione restituisce nil .

Parametri

actionName: string

Il nome dell'azione originariamente passata a BindAction.

Valore predefinito: ""

Restituzioni

Un pulsante immagine creato da BindAction.

Eventi

LocalToolEquipped

Si accende quando il giocatore attuale equipaggia un Tool .

Parametri

toolEquipped: Instance

LocalToolUnequipped

Si accende quando il giocatore attuale disequipaggia un Tool .

Parametri

toolUnequipped: Instance