GuiObject

Visualizza obsoleti

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

Non costruibile
Non Navigabile

GuiObject è una classe astratta (molto come BasePart ) per un oggetto interfaccia utente 2D.Define tutte le proprietà relative alla visualizzazione di un oggetto interfaccia grafica utente (GUI or Intefaccia grafica utente) come Size e Position .Ha anche alcune utili proprietà read-only come AbsolutePosition , AbsoluteSize e AbsoluteRotation .

Per manipolare il layout degli oggetti GUI in modi speciali, puoi utilizzare una struttura di layout come lista/flessibile o griglia e puoi stilare oltre le loro proprietà principali attraverso modificatori di apparenza .

Sebbene sia possibile rilevare gli eventi dei pulsanti del mouse su qualsiasi oggetto GUI utilizzando InputBegan e InputEnded, solo ImageButton e TextButton hanno eventi convenienti dedicati come Activated per rilevare clic/pressione.

Sommario

Proprietà

Proprietà provenienti da GuiBase2d

Metodi

Eventi

Eventi provenienti da GuiBase2d

Proprietà

Active

Lettura Parallela

Questa proprietà determina se il GuiObject sinkerà l'input nel Spazio3D, come i modelli di base con una classe ClickDetector come DragDetector.

Per GuiButton oggetti ( ImageButton e TextButton ), questa proprietà determina se Activated fuochi ( AutoButtonColor funzionerà ancora per quelli anche) .Gli eventi InputBegan, InputChanged e InputEnded funzionano normalmente indipendentemente dal valore di questa Proprietà.

Campioni di codice

This code sample demonstrates the usage of the Active property as a debounce for the Activated event.

TextButton Active Debounce

-- Place this LocalScript within a TextButton (or ImageButton)
local textButton = script.Parent
textButton.Text = "Click me"
textButton.Active = true
local function onActivated()
-- This acts like a debounce
textButton.Active = false
-- Count backwards from 5
for i = 5, 1, -1 do
textButton.Text = "Time: " .. i
task.wait(1)
end
textButton.Text = "Click me"
textButton.Active = true
end
textButton.Activated:Connect(onActivated)

AnchorPoint

Lettura Parallela

Questa proprietà determina il punto di origine di un GuiObject , rispetto alla sua dimensione assoluta.Il punto di origine determina da dove l'elemento è posizionato (attraverso GuiObject.Position ) e da cui si espande il rendering GuiObject.Size .

Vedi qui per i diagrammi illustrati e i dettagli.

Campioni di codice

This code sample moves a UI element to different sides of the parent element. It starts at the top-left and ends at the bottom-right. Paste into a LocalScript in a Frame, within a ScreenGui.

AnchorPoint Demo

local guiObject = script.Parent
while true do
-- Top-left
guiObject.AnchorPoint = Vector2.new(0, 0)
guiObject.Position = UDim2.new(0, 0, 0, 0)
task.wait(1)
-- Top
guiObject.AnchorPoint = Vector2.new(0.5, 0)
guiObject.Position = UDim2.new(0.5, 0, 0, 0)
task.wait(1)
-- Top-right
guiObject.AnchorPoint = Vector2.new(1, 0)
guiObject.Position = UDim2.new(1, 0, 0, 0)
task.wait(1)
-- Left
guiObject.AnchorPoint = Vector2.new(0, 0.5)
guiObject.Position = UDim2.new(0, 0, 0.5, 0)
task.wait(1)
-- Dead center
guiObject.AnchorPoint = Vector2.new(0.5, 0.5)
guiObject.Position = UDim2.new(0.5, 0, 0.5, 0)
task.wait(1)
-- Right
guiObject.AnchorPoint = Vector2.new(1, 0.5)
guiObject.Position = UDim2.new(1, 0, 0.5, 0)
task.wait(1)
-- Bottom-left
guiObject.AnchorPoint = Vector2.new(0, 1)
guiObject.Position = UDim2.new(0, 0, 1, 0)
task.wait(1)
-- Bottom
guiObject.AnchorPoint = Vector2.new(0.5, 1)
guiObject.Position = UDim2.new(0.5, 0, 1, 0)
task.wait(1)
-- Bottom-right
guiObject.AnchorPoint = Vector2.new(1, 1)
guiObject.Position = UDim2.new(1, 0, 1, 0)
task.wait(1)
end

AutomaticSize

Lettura Parallela

Questa proprietà viene utilizzata per ridimensionare automaticamente gli oggetti dell'interfaccia utente padre in base alle dimensioni dei suoi discendenti.Puoi utilizzare questa proprietà per aggiungere dinamicamente testo e altri contenuti a un oggetto UI durante l'edizione o l'esecuzione, e la dimensione si adatterà a quel contenuto.

Quando AutomaticSize è impostato su un valore Enum.AutomaticSize a qualunque cosa diversa da None, questo oggetto UI può ridimensionarsi a seconda del suo contenuto figlio.

Per ulteriori informazioni su come utilizzare questa proprietà e su come funziona, vedi qui.

Campioni di codice

The following script creates an automatically-sized parent frame with aUIListLayout, then it inserts several automatically-sized TextLabel objects. Note how the parent UIListLayout automatically resizes to fit its child content and the labels automatically resize to fit their text content. This script can be parented to a ScreenGui.

LocalScript in a ScreenGui

-- Array of text labels/fonts/sizes to output
local labelArray = {
{ text = "Lorem", font = Enum.Font.Creepster, size = 50 },
{ text = "ipsum", font = Enum.Font.IndieFlower, size = 35 },
{ text = "dolor", font = Enum.Font.Antique, size = 55 },
{ text = "sit", font = Enum.Font.SpecialElite, size = 65 },
{ text = "amet", font = Enum.Font.FredokaOne, size = 40 },
}
-- Create an automatically-sized parent frame
local parentFrame = Instance.new("Frame")
parentFrame.AutomaticSize = Enum.AutomaticSize.XY
parentFrame.BackgroundColor3 = Color3.fromRGB(90, 90, 90)
parentFrame.Size = UDim2.fromOffset(25, 100)
parentFrame.Position = UDim2.fromScale(0.1, 0.1)
parentFrame.Parent = script.Parent
-- Add a list layout
local listLayout = Instance.new("UIListLayout")
listLayout.Padding = UDim.new(0, 5)
listLayout.Parent = parentFrame
-- Set rounded corners and padding for visual aesthetics
local roundedCornerParent = Instance.new("UICorner")
roundedCornerParent.Parent = parentFrame
local uiPaddingParent = Instance.new("UIPadding")
uiPaddingParent.PaddingTop = UDim.new(0, 5)
uiPaddingParent.PaddingLeft = UDim.new(0, 5)
uiPaddingParent.PaddingRight = UDim.new(0, 5)
uiPaddingParent.PaddingBottom = UDim.new(0, 5)
uiPaddingParent.Parent = parentFrame
for i = 1, #labelArray do
-- Create an automatically-sized text label from array
local childLabel = Instance.new("TextLabel")
childLabel.AutomaticSize = Enum.AutomaticSize.XY
childLabel.Size = UDim2.fromOffset(75, 15)
childLabel.Text = labelArray[i]["text"]
childLabel.Font = labelArray[i]["font"]
childLabel.TextSize = labelArray[i]["size"]
childLabel.TextColor3 = Color3.new(1, 1, 1)
childLabel.Parent = parentFrame
-- Visual aesthetics
local roundedCorner = Instance.new("UICorner")
roundedCorner.Parent = childLabel
local uiPadding = Instance.new("UIPadding")
uiPadding.PaddingTop = UDim.new(0, 5)
uiPadding.PaddingLeft = UDim.new(0, 5)
uiPadding.PaddingRight = UDim.new(0, 5)
uiPadding.PaddingBottom = UDim.new(0, 5)
uiPadding.Parent = childLabel
task.wait(2)
end

BackgroundColor3

Lettura Parallela

Questa proprietà determina il colore di uno sfondo GuiObject (il colore di riempimento).Se il tuo elemento contiene testo, come un TextBox , TextButton o TextLabel , assicurati che il colore del tuo sfondo contrasti con il colore del testo.

Un'altra proprietà che determina le proprietà visive del background è GuiObject.BackgroundTransparency ; se questa è impostata su 1, né il background né il bordo verranno Renderizzare.

Vedi anche BorderColor3 .

Campioni di codice

This code sample causes a parent Frame to loop through all colors of the rainbow using Color3.fromHSV.

Rainbow Frame

-- Put this code in a LocalScript in a Frame
local frame = script.Parent
while true do
for hue = 0, 255, 4 do
-- HSV = hue, saturation, value
-- If we loop from 0 to 1 repeatedly, we get a rainbow!
frame.BorderColor3 = Color3.fromHSV(hue / 256, 1, 1)
frame.BackgroundColor3 = Color3.fromHSV(hue / 256, 0.5, 0.8)
task.wait()
end
end

BackgroundTransparency

Lettura Parallela

Questa proprietà determina la trasparenza del GuiObject.Non determina, tuttavia, la trasparenza del testo se la GUI è una TextBox , TextButton , o TextLabel ; la trasparenza del testo viene determinata TextBox.TextTransparency , TextButton.TextTransparency , e TextLabel.TextTransparency rispettivamente.

Se questa proprietà è impostata su 1, né lo sfondo né il bordo verranno visualizzati e lo sfondo GUI sarà completamente trasparente.

BorderColor3

Lettura Parallela

Determina il colore del bordo rettangolare GuiObject (anche noto come colore del tratto).Questo è separato dall'oggetto GuiObject.BackgroundColor3 .Non sarai in grado di vedere il bordo dell'oggetto se la sua proprietà GuiObject.BorderSizePixel è impostata su 0 .

Nota che il componente UIStroke consente effetti di bordo più avanzati.

Campioni di codice

This code sample causes the border of a parent GuiObject to highlight when the user hovers their mouse over the element.

Button Highlight

-- Put me inside some GuiObject, preferrably an ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Yellow
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Black
end
-- Connect events
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Our default state is "not hovered"
onLeave()

BorderMode

Lettura Parallela

Questa proprietà determina in che modo il bordo GuiObject viene disposto rispetto alle sue dimensioni utilizzando l'enumerazione dello stesso nome, Enum.BorderMode .

Nota che UIStroke può sovrascrivere questa proprietà e consentire effetti di bordo più avanzati.

BorderSizePixel

Lettura Parallela

Questa proprietà determina quanto è ampio il rendering del bordo GuiObject, in pixel. Impostare questo a 0 disabilita completamente il bordo.

Nota che UIStroke può sovrascrivere questa proprietà e consentire effetti di bordo più avanzati.

Campioni di codice

This code sample causes the border of a parent GuiObject to highlight when the user hovers their mouse over the element.

Button Highlight

-- Put me inside some GuiObject, preferrably an ImageButton/TextButton
local button = script.Parent
local function onEnter()
button.BorderSizePixel = 2
button.BorderColor3 = Color3.new(1, 1, 0) -- Yellow
end
local function onLeave()
button.BorderSizePixel = 1
button.BorderColor3 = Color3.new(0, 0, 0) -- Black
end
-- Connect events
button.MouseEnter:Connect(onEnter)
button.MouseLeave:Connect(onLeave)
-- Our default state is "not hovered"
onLeave()

ClipsDescendants

Lettura Parallela

Questa proprietà determina se il GuiObject renderizzerà (renderizzerà invisibile) qualsiasi porzione degli elementi GUI discendenti che altrimenti renderebbe fuori dai confini del rettangolo.

Nota che Rotation non è supportata da questa Proprietà.Se questa o qualsiasi antenato GUI ha un non zero , questa proprietà viene ignorata e gli elementi GUI discendenti verranno resi indipendentemente dal valore di questa Proprietà.

Sola Lettura
Non Replicato
Lettura Parallela

Quando il dito del Giocatoreviene toccato e tenuto premuto sul GuiObject, il GuiState di GuiObject verrà impostato su Press .Allo stesso modo, quando il dito del Giocatoreviene rilasciato dal GuiObject , il GuiState del GuiObject verrà impostato su Idle , e quando Interactable viene spento sul GuiObject , il Class.GuiState del GuiObject verrà impostato su NonInteractable.

Interactable

Lettura Parallela

Determina se il GuiButton può essere interagito o meno, o se il GuiState del GuiObject sta cambiando o meno.

Su un GuiButton :

Su un GuiObject :

LayoutOrder

Lettura Parallela

Questa proprietà controlla l'ordine di classificazione del GuiObject quando si utilizza un UIGridStyleLayout (come UIListLayout o UIPageLayout ) con SortOrder impostato a Enum.SortOrder.LayoutOrder .Non ha funzionalità se l'oggetto non ha una struttura di layout UI fratello.

GuiObjects sono ordinati in ordine crescente in cui i valori più bassi hanno la priorità sui valori più alti.Gli oggetti con valori uguali tornano all'ordine in cui sono stati aggiunti.

Se non sei sicuro se dovrai aggiungere un elemento tra due elementi esistenti in futuro, è una buona pratica utilizzare i multipli di 100 ( 0 , 100 , 200 , ecc.).Questo garantisce un grande gap di valori di ordine di layout che puoi utilizzare per gli elementi ordinati tra gli altri elementi.

Vedi anche che determina l'ordine di rendering dell'oggetto invece dell'ordine di classificazione.

NextSelectionDown

Lettura Parallela

Questa proprietà imposta il GuiObject selezionato quando l'utente sposta il selettore del gamepad verso il basso.Se questa proprietà è vuota, spostare il gamepad verso il basso non cambierà l'GUI or Intefaccia grafica utenteselezionata.

Spostare il selettore del gamepad verso il basso imposta il GuiService.SelectedObject a questo oggetto a meno che la GUI non sia Selectable .Nota che questa proprietà può essere impostata su un elemento GUI anche se non è Selectable, quindi devi assicurarti che il valore di una proprietà selezionabile di GUI or Intefaccia grafica utentecorrisponda al tuo comportamento previsto.

Vedi anche NextSelectionUp , NextSelectionLeft e NextSelectionRight .

Campioni di codice

This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.

Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.

The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:

  1. Starting with 1, the name of all GUI elements match their position in the grid
  2. Left: The item to the left will always be numbered 1 less than the current element
  3. Right: The item to the left will always be numbered 1 more than the current element
  4. Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
  5. Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.

This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.

Creating a Gamepad Selection Grid

-- Setup the Gamepad selection grid using the code below
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)

NextSelectionLeft

Lettura Parallela

Questa proprietà imposta il GuiObject selezionato quando l'utente sposta il selettore del gamepad a sinistra.Se questa proprietà è vuota, spostare il gamepad a sinistra non cambierà l'GUI or Intefaccia grafica utenteselezionata.

Spostare il selettore del gamepad a sinistra imposta il GuiService.SelectedObject a questo oggetto a meno che la GUI non sia Selectable .Nota che questa proprietà può essere impostata su un elemento GUI anche se non è Selectable, quindi devi assicurarti che il valore di una proprietà selezionabile di GUI or Intefaccia grafica utentecorrisponda al tuo comportamento previsto.

Vedi anche NextSelectionUp , NextSelectionDown e NextSelectionRight .

Campioni di codice

This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.

Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.

The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:

  1. Starting with 1, the name of all GUI elements match their position in the grid
  2. Left: The item to the left will always be numbered 1 less than the current element
  3. Right: The item to the left will always be numbered 1 more than the current element
  4. Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
  5. Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.

This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.

Creating a Gamepad Selection Grid

-- Setup the Gamepad selection grid using the code below
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)

NextSelectionRight

Lettura Parallela

Questa proprietà imposta il GuiObject selezionato quando l'utente sposta il selettore del gamepad a destra.Se questa proprietà è vuota, spostare il gamepad a destra non cambierà l'GUI or Intefaccia grafica utenteselezionata.

Spostare il selettore del gamepad a destra imposta il GuiService.SelectedObject a questo oggetto a meno che la GUI non sia Selectable .Nota che questa proprietà può essere impostata su un elemento GUI anche se non è Selectable, quindi devi assicurarti che il valore di una proprietà selezionabile di GUI or Intefaccia grafica utentecorrisponda al tuo comportamento previsto.

Vedi anche NextSelectionUp , NextSelectionDown e NextSelectionLeft .

Campioni di codice

This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.

Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.

The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:

  1. Starting with 1, the name of all GUI elements match their position in the grid
  2. Left: The item to the left will always be numbered 1 less than the current element
  3. Right: The item to the left will always be numbered 1 more than the current element
  4. Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
  5. Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.

This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.

Creating a Gamepad Selection Grid

-- Setup the Gamepad selection grid using the code below
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)

NextSelectionUp

Lettura Parallela

Questa proprietà imposta il GuiObject selezionato quando l'utente sposta il selettore del gamepad verso l'alto.Se questa proprietà è vuota, spostare il gamepad verso l'alto non cambierà l'GUI or Intefaccia grafica utenteselezionata.

Spostare il selettore del gamepad verso l'alto imposta il GuiService.SelectedObject a questo oggetto a meno che la GUI non sia Selectable .Nota che questa proprietà può essere impostata su un elemento GUI anche se non è Selectable, quindi devi assicurarti che il valore di una proprietà selezionabile di GUI or Intefaccia grafica utentecorrisponda al tuo comportamento previsto.

Vedi anche NextSelectionDown , NextSelectionLeft , NextSelectionRight .

Campioni di codice

This example demonstrates how to enable Gamepad navigation through a grid of GuiObject|GUI elements without manually having to connect the GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, and GuiObject|NextSelectionRight, and GuiObject.NextSelectionLeft properties for every element in the grid.

Note that this code sample assumes your UIGridLayout is sorted by name, where elements are named in successive numerical order.

The code relies on this to set the NextSelection properties for all GuiObjects in the same level as the UIGridLayout. In our example, the UIGridLayoutObject and GUI elements within the grid are all children of a Frame named "Container". The code gets the children of "Container" and loops through each child. Children that are not GuiObjects are ignored. For each GUI element, the code attempts to assigned the NextSelection properties using the following logic:

  1. Starting with 1, the name of all GUI elements match their position in the grid
  2. Left: The item to the left will always be numbered 1 less than the current element
  3. Right: The item to the left will always be numbered 1 more than the current element
  4. Up: The item above (up) will always be number of GUIs in a row 1 less than the current element
  5. Down: The item below (down) will always be the number of GUIs in a row more than the current element This logic also allows for the GUI elements at the begging and end of rows (excluding the first and last element) to wrap around to the next and previous rows. If an element doesn't exist to the left, right, up, or down, the NextSelection will remain nil and moving the Gamepad selector in the direction will not change the selected GUI.

This example also contains code to test the grid using the arrow keys (Up, Down, Left, Right) of your keyboard instead of a gamepad, just in case you don't have a gamepad to test with. This portion of code initially selects the element named "1" by assigning it to the GuiService.SelectedObject property.

Creating a Gamepad Selection Grid

-- Setup the Gamepad selection grid using the code below
local container = script.Parent:FindFirstChild("Container")
local grid = container:GetChildren()
local rowSize = container:FindFirstChild("UIGridLayout").FillDirectionMaxCells
for _, gui in pairs(grid) do
if gui:IsA("GuiObject") then
local pos = gui.Name
-- Left edge
gui.NextSelectionLeft = container:FindFirstChild(pos - 1)
-- Right edge
gui.NextSelectionRight = container:FindFirstChild(pos + 1)
-- Above
gui.NextSelectionUp = container:FindFirstChild(pos - rowSize)
-- Below
gui.NextSelectionDown = container:FindFirstChild(pos + rowSize)
end
end
-- Test the Gamepad selection grid using the code below
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
GuiService.SelectedObject = container:FindFirstChild("1")
function updateSelection(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
local key = input.KeyCode
local selectedObject = GuiService.SelectedObject
if not selectedObject then
return
end
if key == Enum.KeyCode.Up then
if not selectedObject.NextSelectionUp then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Down then
if not selectedObject.NextSelectionDown then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Left then
if not selectedObject.NextSelectionLeft then
GuiService.SelectedObject = selectedObject
end
elseif key == Enum.KeyCode.Right then
if not selectedObject.NextSelectionRight then
GuiService.SelectedObject = selectedObject
end
end
end
end
UserInputService.InputBegan:Connect(updateSelection)

Position

Lettura Parallela

Questa proprietà determina il pixel e la posizione scalare usando un . La posizione è centrata attorno alla posizione dell'oggetto .

La posizione scalare è relativa alla dimensione dell'elemento GUI padre, se presente.

Le porzioni di pixel del valore UDim2 sono uguali indipendentemente dalla dimensione della GUI or Intefaccia grafica utentepadre.I valori rappresentano la posizione dell'oggetto in pixel.La posizione effettiva dei pixel di un oggetto può essere letta dalla ProprietàGuiBase2d.AbsolutePosition.

Rotation

Lettura Parallela

Questa proprietà determina il numero di gradi con cui il GuiObject viene ruotato.La rotazione è relativa al centro dell'oggetto, non il >, intendendo che non puoi cambiare il punto di rotazione.Inoltre, questa proprietà non è compatibile con ClipsDescendants .

Selectable

Lettura Parallela

Questa proprietà determina se la GuiObject può essere selezionata quando si naviga nelle interfacce grafiche utilizzando un gamepad.

Se questa proprietà è true, può essere selezionata una GUI. Selezionare una GUI imposta anche la proprietà GuiService.SelectedObject a quell'oggetto.

Quando questo è false, la GUI non può essere selezionata.Tuttavia, impostare questo a false quando una GUI viene selezionata non lo deselezionerà né cambierà il valore della ProprietàGuiService.SelectedObject.

Aggiungi GuiObject.SelectionGained e GuiObject.SelectionLost non verrà fuocato per l'elemento. Per deselezionare un GuiObject, devi cambiare la ProprietàGuiService.SelectedObject.

Questa proprietà è utile se una GUI è connessa a diverse GUI tramite proprietà come questa GuiObject.NextSelectionUp , GuiObject.NextSelectionDown , NextSelectionRight , o NextSelectionLeft .Piuttosto che cambiare tutte le proprietà in modo che il Gamepad non possa selezionare l'GUI or Intefaccia grafica utentegrafica, puoi disabilitare la sua proprietà Selezionabile per impedirne temporaneamente la selezione.Quindi, quando vuoi che il selettore del gamepad sia in grado di selezionare l'GUI or Intefaccia grafica utentegrafica, riabilita semplicemente la sua Proprietàselezionabile.

Campioni di codice

The example below offers a simple demonstration on how to use the GuiObject.Selectable property to limit when a GUI element can be selected by the Gamepad navigator.

When a TextBox has gains focus, it can be selected. However, when a TextBox loses focus it can no longer be selected.

Although this is a simple demonstration, the property can also be used to prevent the navigator from selecting UI elements that exist for cosmetic rather than functional purposes. For instance, while the buttons on a menu screen should be selectable, the title image should not be.

Limiting TextBox Selection

local GuiService = game:GetService("GuiService")
local textBox = script.Parent
local function gainFocus()
textBox.Selectable = true
GuiService.SelectedObject = textBox
end
local function loseFocus(_enterPressed, _inputObject)
GuiService.SelectedObject = nil
textBox.Selectable = false
end
-- The FocusLost and FocusGained event will fire because the textBox
-- is of type TextBox
textBox.Focused:Connect(gainFocus)
textBox.FocusLost:Connect(loseFocus)

SelectionImageObject

Lettura Parallela

Questa proprietà sostituisce l'adorno di selezione predefinito utilizzato per i gamepad.

Nota che gli overlay scelti SelectionImageObject sovrappongono il selezionato GuiObject con il Size dell'immagine.Per ottenere i migliori risultati, dovresti ridimensionare il personalizzato SelectionImageObject via i valori della scala UDim2 per aiutare a garantire che l'oggetto si ridimensioni correttamente sull'elemento selezionato.

Cambiare il SelectionImageObject per un elemento GuiObject influisce solo su quell'elemento. Per influenzare tutti gli elementi GUI di un utente, imposta la ProprietàPlayerGui.SelectionImageObject.

Per determinare o impostare quale elemento GUI è selezionato dall'utente, puoi usare la ProprietàGuiService.SelectedObject.Il giocatore utilizza il gamepad per selezionare diversi elementi GUI, invocando gli eventi NextSelectionUp, NextSelectionDown, NextSelectionLeft e NextSelectionRight.

SelectionOrder

Lettura Parallela

Gli oggetti Gui con un ordine di selezione più basso vengono selezionati prima degli oggetti Gui con un ordine di selezione più alto quando si avvia la selezione del gamepad o si chiama GuiService:Select() su un antenato.Questa proprietà non influisce sulla navigazione direzionale.Il valore predefinito è 0.

Size

Lettura Parallela

Questa proprietà determina la dimensione GuiObject scala e pixel utilizzando un UDim2 .

La dimensione scalare è relativa alla dimensione dell'elemento GUI padre, se presente.

Le porzioni di pixel del valore UDim2 sono uguali indipendentemente dalla dimensione della GUI or Intefaccia grafica utentepadre.I valori rappresentano la dimensione dell'oggetto in pixel.La dimensione effettiva dei pixel di un oggetto può essere letta dalla ProprietàGuiBase2d.AbsoluteSize .

Se il GuiObject ha un parent, la sua dimensione lungo ciascun asse è influenzata anche dalla dimensione del parentSizeConstraint.

Campioni di codice

This code sample allows you to create a simple color-changing health bar using two nested Frames. Paste this into a LocalScript on the inner frame.

Health Bar

local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Paste script into a LocalScript that is
-- parented to a Frame within a Frame
local frame = script.Parent
local container = frame.Parent
container.BackgroundColor3 = Color3.new(0, 0, 0) -- black
-- This function is called when the humanoid's health changes
local function onHealthChanged()
local human = player.Character.Humanoid
local percent = human.Health / human.MaxHealth
-- Change the size of the inner bar
frame.Size = UDim2.new(percent, 0, 1, 0)
-- Change the color of the health bar
if percent < 0.1 then
frame.BackgroundColor3 = Color3.new(1, 0, 0) -- black
elseif percent < 0.4 then
frame.BackgroundColor3 = Color3.new(1, 1, 0) -- yellow
else
frame.BackgroundColor3 = Color3.new(0, 1, 0) -- green
end
end
-- This function runs is called the player spawns in
local function onCharacterAdded(character)
local human = character:WaitForChild("Humanoid")
-- Pattern: update once now, then any time the health changes
human.HealthChanged:Connect(onHealthChanged)
onHealthChanged()
end
-- Connect our spawn listener; call it if already spawned
player.CharacterAdded:Connect(onCharacterAdded)
if player.Character then
onCharacterAdded(player.Character)
end

SizeConstraint

Lettura Parallela

Questa proprietà imposta gli assi Size su cui si baserà il GuiObject , rispetto alla dimensione del suo parent.

Questa proprietà è utile per creare oggetti GUI che sono destinati a scalare con la larghezza o l'altezza di un oggetto padre, ma non entrambi, preservando efficacemente la proporzione aspetto dell'oggetto.

Transparency

Nascosto
Non Replicato
Lettura Parallela

Una proprietà mista di BackgroundTransparency e TextTransparency.

Visible

Lettura Parallela

Questa proprietà se la GuiObject e i suoi discendenti saranno resi.

Il rendering di singoli componenti di un GuiObject può essere controllato individualmente attraverso le proprietà di trasparenza come GuiObject.BackgroundTransparency , TextLabel.TextTransparency e ImageLabel.ImageTransparency .

Quando questa proprietà è false , la GuiObject verrà ignorata da strutture di layout come UIListLayout , UIGridLayout e UITableLayout .In altre parole, lo spazio che l'elemento altrimenti occuperebbe nel layout viene utilizzato da altri elementi invece.

Campioni di codice

This code sample adds open/close functionality to a Window UI. Paste as a LocalScript that is a sibling of a Frame named Window, a TextButton/ImageButton named Window, and a TextButton/ImageButton within the Window called Close.

UI Window

local gui = script.Parent
local window = gui:WaitForChild("Window")
local toggleButton = gui:WaitForChild("ToggleWindow")
local closeButton = window:WaitForChild("Close")
local function toggleWindowVisbility()
-- Flip a boolean using the `not` keyword
window.Visible = not window.Visible
end
toggleButton.Activated:Connect(toggleWindowVisbility)
closeButton.Activated:Connect(toggleWindowVisbility)

ZIndex

Lettura Parallela

Questa proprietà determina l'ordine in cui un GuiObject rende relativamente agli altri.

Per impostazione predefinita, GuiObjects rendere in ordine crescente di priorità dove quelli con valori più bassi ZIndex vengono visualizzati sotto quelli con valori più alti.Puoi cambiare l'ordine di rendering all'interno di un ScreenGui , SurfaceGui , o BillboardGui cambiando il valore del suo ZIndexBehavior .

Se non sei sicuro se dovrai aggiungere un elemento tra due elementi esistenti in futuro, è una buona pratica utilizzare i multipli di 100 ( 0 , 100 , 200 , ecc.).Questo garantisce un grande gap di valori dell'ordine di rendering che puoi utilizzare per gli elementi stratificati tra gli altri elementi.

Vedi anche LayoutOrder che controlla l'ordine di ordinamento di un GuiObject quando viene utilizzato con una struttura di layout come UIListLayout o UIGridLayout .

Metodi

TweenPosition

Sposta lisciamente una GUI in una nuova posizione UDim2 in un tempo specificato utilizzando la posizione specificata Enum.EasingDirection e Enum.EasingStyle.

Questa funzione restituirà se il tween si Giocare.Non si riproducirà se un altro pre-adolescente sta agendo sul GuiObject e il parametro di sovrascarica è false .

Vedi anche GuiObject:TweenSize() e GuiObject:TweenSizeAndPosition() .

Parametri

endPosition: UDim2

Dove la GUI dovrebbe muoversi.

Valore predefinito: ""
easingDirection: Enum.EasingDirection

La direzione in cui facilitare la GUI alla posizione finale endPosition.

Valore predefinito: "Out"
easingStyle: Enum.EasingStyle

Lo stile in cui facilitare la GUI alla posizione finale.

Valore predefinito: "Quad"
time: number

Per quanto tempo, in secondi, il tween dovrebbe prendere per completarsi.

Valore predefinito: 1
override: boolean

Se il tween sostituirà un gemellatiin corso.

Valore predefinito: false
callback: function

Una funzione di richiamo da eseguire quando il tween si conclude.

Valore predefinito: "nil"

Restituzioni

Se il tween si Giocare.

Campioni di codice

This code sample demonstrates a more involved usage of TweenPosition by detecting when the tween completes/cancels by defining a callback function. It also prints whether the tween will play.

Tween a GUI's Position

local START_POSITION = UDim2.new(0, 0, 0, 0)
local GOAL_POSITION = UDim2.new(1, 0, 1, 0)
local guiObject = script.Parent
local function callback(state)
if state == Enum.TweenStatus.Completed then
print("The tween completed uninterrupted")
elseif state == Enum.TweenStatus.Canceled then
print("Another tween cancelled this one")
end
end
-- Initialize the GuiObject position, then start the tween:
guiObject.Position = START_POSITION
local willPlay = guiObject:TweenPosition(
GOAL_POSITION, -- Final position the tween should reach
Enum.EasingDirection.In, -- Direction of the easing
Enum.EasingStyle.Sine, -- Kind of easing to apply
2, -- Duration of the tween in seconds
true, -- Whether in-progress tweens are interrupted
callback -- Function to be callled when on completion/cancelation
)
if willPlay then
print("The tween will play")
else
print("The tween will not play")
end

TweenSize

Ridimensiona lisciamente un GuiObject a un nuovo UDim2 nel tempo specificato utilizzando il Enum.EasingDirection e il Enum.EasingStyle specificati.

Questa funzione restituirà se il tween si Giocare.Normalmente questo restituirà sempre true , ma restituirà false se un altro pre-adolescente è attivo e l' override è impostato su false .

Vedi anche GuiObject:TweenSize() e GuiObject:TweenSizeAndPosition() .

Parametri

endSize: UDim2

La dimensione che la GUI dovrebbe Ridimensiona.

Valore predefinito: ""
easingDirection: Enum.EasingDirection

La direzione in cui facilitare la GUI al endSize .

Valore predefinito: "Out"
easingStyle: Enum.EasingStyle

Lo stile in cui facilitare l'interfaccia grafica al endSize.

Valore predefinito: "Quad"
time: number

Per quanto tempo, in secondi, il tween dovrebbe prendere per completarsi.

Valore predefinito: 1
override: boolean

Se il tween sostituirà un gemellatiin corso.

Valore predefinito: false
callback: function

Una funzione di richiamo da eseguire quando il tween si conclude.

Valore predefinito: "nil"

Restituzioni

Se il tween si Giocare.

Campioni di codice

This code sample demonstrates the usage of the GuiObject:TweenSize() function. It initiates an animation on the parent's GuiObject.Size property to UDim2.new(0.5, 0, 0.5, 0), which is half the GuiObject's parent size on both axes.

Additionally, it demonstrates how the callback parameter can be used to detect when the tween stops (whether it was cancelled by another tween or completed).

Tween a GuiObject's Size

local guiObject = script.Parent
local function callback(didComplete)
if didComplete then
print("The tween completed successfully")
else
print("The tween was cancelled")
end
end
local willTween = guiObject:TweenSize(
UDim2.new(0.5, 0, 0.5, 0), -- endSize (required)
Enum.EasingDirection.In, -- easingDirection (default Out)
Enum.EasingStyle.Sine, -- easingStyle (default Quad)
2, -- time (default: 1)
true, -- should this tween override ones in-progress? (default: false)
callback -- a function to call when the tween completes (default: nil)
)
if willTween then
print("The GuiObject will tween")
else
print("The GuiObject will not tween")
end

TweenSizeAndPosition

Ridimensiona e sposta agevolmente una GUI a una nuova dimensione e posizione e > utilizzando le dimensioni e le posizioni specificate e > .

Questa funzione restituirà se il tween si Giocare.Normalmente questo restituirà sempre true , ma restituirà false se un altro pre-adolescente è attivo e l' override è impostato su false .

Vedi anche GuiObject:TweenSize() e GuiObject:TweenSizeAndPosition() .

Parametri

endSize: UDim2

La dimensione che la GUI dovrebbe Ridimensiona.

Valore predefinito: ""
endPosition: UDim2

Dove la GUI dovrebbe muoversi.

Valore predefinito: ""
easingDirection: Enum.EasingDirection

La direzione in cui facilitare la GUI al endSize e endPosition .

Valore predefinito: "Out"
easingStyle: Enum.EasingStyle

Lo stile in cui facilitare l'interfaccia grafica al endSize e endPosition .

Valore predefinito: "Quad"
time: number

Per quanto tempo, in secondi, il tween dovrebbe prendere per completarsi.

Valore predefinito: 1
override: boolean

Se il tween sostituirà un gemellatiin corso.

Valore predefinito: false
callback: function

Una funzione di richiamo da eseguire quando il tween si conclude.

Valore predefinito: "nil"

Restituzioni

Se il tween si Giocare.

Campioni di codice

The below example would tween a Frame to the top left of the parent's size and resize it down to 0.

Tween a GUI's Size and Position

local frame = script.Parent.Frame
frame:TweenSizeAndPosition(UDim2.new(0, 0, 0, 0), UDim2.new(0, 0, 0, 0))

Eventi

InputBegan

Questo evento si attiva quando un utente inizia a interagire con il GuiObject attraverso un dispositivo Interfaccia Uomo-Computer (pulsante del mouse giù, tocco di inizio, pulsante della tastiera giù, ecc.).

Il UserInputService ha un evento di nome simile che non è limitato a un elemento UI specifico: UserInputService.InputBegan .

Questo evento si attiverà sempre indipendentemente dallo stato del gioco.

Vedi anche GuiObject.InputEnded e GuiObject.InputChanged .

Parametri

Un InputObject , che contiene dati utili per interrogare l'input dell'utente come il type of input , state of input e screen coordinates of the input .


Campioni di codice

The following example demonstrates one of many usage examples of handling user input from InputBegan depending on its type.

In order for this to work as expected, it must be placed in a LocalScript and a child of gui.

Tracking the Beginning of Input on a GuiObject

-- In order to use the InputBegan event, you must specify the GuiObject
local gui = script.Parent
-- A sample function providing multiple usage cases for various types of user input
local function inputBegan(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key is being pushed down! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has started at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button is being pressed on a gamepad! Button:", input.KeyCode)
end
end
gui.InputBegan:Connect(inputBegan)

InputChanged

Questo evento si attiva quando un utente cambia il modo in cui interagisce tramite un dispositivo Interfaccia Uomo-Computer (tasto del mouse verso il basso, tocco di inizio, pulsante della tastiera verso il basso, ecc.).

Il UserInputService ha un evento di nome simile che non è limitato a un elemento UI specifico: UserInputService.InputChanged .

Questo evento si attiverà sempre indipendentemente dallo stato del gioco.

Vedi anche GuiObject.InputBegan e GuiObject.InputEnded .

Parametri

Un InputObject , che contiene dati utili per interrogare l'input dell'utente come il type of input , state of input e screen coordinates of the input .


Campioni di codice

The following example demonstrates one of many usage examples of handling user input from InputChanged depending on its type.

In order for this to work as expected, it must be placed in a LocalScript and a child of gui.

GuiObject InputChanged Demo

local UserInputService = game:GetService("UserInputService")
local gui = script.Parent
local function printMovement(input)
print("Position:", input.Position)
print("Movement Delta:", input.Delta)
end
local function inputChanged(input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
print("The mouse has been moved!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
print("The mouse wheel has been scrolled!")
print("Wheel Movement:", input.Position.Z)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
if input.KeyCode == Enum.KeyCode.Thumbstick1 then
print("The left thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.Thumbstick2 then
print("The right thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.ButtonL2 then
print("The pressure being applied to the left trigger has changed!")
print("Pressure:", input.Position.Z)
elseif input.KeyCode == Enum.KeyCode.ButtonR2 then
print("The pressure being applied to the right trigger has changed!")
print("Pressure:", input.Position.Z)
end
elseif input.UserInputType == Enum.UserInputType.Touch then
print("The user's finger is moving on the screen!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.Gyro then
local _rotInput, rotCFrame = UserInputService:GetDeviceRotation()
local rotX, rotY, rotZ = rotCFrame:toEulerAnglesXYZ()
local rot = Vector3.new(math.deg(rotX), math.deg(rotY), math.deg(rotZ))
print("The rotation of the user's mobile device has been changed!")
print("Position", rotCFrame.p)
print("Rotation:", rot)
elseif input.UserInputType == Enum.UserInputType.Accelerometer then
print("The acceleration of the user's mobile device has been changed!")
printMovement(input)
end
end
gui.InputChanged:Connect(inputChanged)

InputEnded

L'evento InputEnded si attiva quando un utente smette di interagire tramite un dispositivo di interfaccia uomo-computer (tasto del mouse giù, tocco inizio, pulsante della tastiera giù, ecc.).

Il UserInputService ha un evento di nome simile che non è limitato a un elemento UI specifico: UserInputService.InputEnded .

Questo evento si attiverà sempre indipendentemente dallo stato del gioco.

Vedi anche GuiObject.InputBegan e GuiObject.InputChanged .

Parametri

Un InputObject , che contiene dati utili per interrogare l'input dell'utente come il Enum.UserInputType , Enum.UserInputState e InputObject.Position .


Campioni di codice

The following example demonstrates one of many usage examples of handling user input from InputEnded depending on its type.

In order for this to work as expected, it must be placed in a LocalScript and a child of gui.

Tracking the End of Input on a GuiObject

-- In order to use the InputChanged event, you must specify a GuiObject
local gui = script.Parent
-- A sample function providing multiple usage cases for various types of user input
local function inputEnded(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key has been released! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button has been released on a gamepad! Button:", input.KeyCode)
end
end
gui.InputEnded:Connect(inputEnded)

MouseEnter

L'evento MouseEnter si attiva quando un utente muove il mouse in un elemento GuiObject .

Si prega di non fare affidamento sugli argomenti x e y passati da questo evento come modo infallibile per determinare dove si trova il mouse dell'utente quando entra in una GUI or Intefaccia grafica utente.Queste coordinate possono variare anche quando il mouse entra nella GUI attraverso lo stesso bordo - in particolare quando il mouse entra nell'elemento rapidamente.Questo è dovuto al fatto che le coordinate indicano la posizione del mouse quando si attiva l'evento piuttosto che l'esatto momento in cui il mouse entra nella GUI or Intefaccia grafica utente.

Questo evento si attiva anche quando l'elemento GUI si rende sotto un altro elemento.

Se vuoi tracciare quando il mouse di un utente lascia un elemento GUI, puoi usare l'evento GuiObject.MouseLeave.

Vedi anche

Parametri

Le coordinate dello schermo X del Topo, or mouse as computer mousein pixel, relative all'angolo superiore sinistro dello schermo.

Le coordinate dello schermo del Topo, or mouse as computer mouse Y in pixel, relative all'angolo superiore sinistro dello schermo.


Campioni di codice

The following example prints the mouse location, in pixels, when it enters GUI element.

Printing where a Mouse Enters a GuiObject

local guiObject = script.Parent
guiObject.MouseEnter:Connect(function(x, y)
print("The user's mouse cursor has entered the GuiObject at position", x, ",", y)
end)

MouseLeave

L'evento MouseLeave si attiva quando un utente muove il mouse fuori da un elemento GuiObject .

Si prega di non fare affidamento sugli argomenti x e y passati da questo evento come modo infallibile per determinare dove si trova il mouse dell'utente quando esce da una GUI or Intefaccia grafica utente.Queste coordinate possono variare anche quando il mouse lascia la GUI or Intefaccia grafica utenteattraverso lo stesso bordo - in particolare quando il mouse lascia l'elemento rapidamente.Questo è dovuto al fatto che le coordinate indicano la posizione del mouse quando si attiva l'evento piuttosto che l'esatto momento in cui il mouse lascia l'interfaccia grafica.

Questo evento si attiva anche quando l'elemento GUI si rende sotto un altro elemento.

Vedi anche

Parametri

Le coordinate dello schermo X del Topo, or mouse as computer mousein pixel, relative all'angolo superiore sinistro dello schermo.

Le coordinate dello schermo del Topo, or mouse as computer mouse Y in pixel, relative all'angolo superiore sinistro dello schermo.


MouseMoved

Si attiva ogni volta che un utente muove il mouse mentre è all'interno di un elemento GuiObject .È simile a Mouse.Move , che si attiva indipendentemente se il mouse dell'utente è su un elemento GUI.

Nota, questo evento si attiva quando viene aggiornata la posizione del Topo, or mouse as computer mouse, quindi si attiverà ripetutamente mentre viene spostato.

Gli argomenti x e y indicano le coordinate dello schermo aggiornate del mouse dell'utente in pixel.Questi possono essere utili per determinare la posizione del Topo, or mouse as computer mousesulla GUI or Intefaccia grafica utente, sullo schermo e sul delta poiché la posizione precedente del Topo, or mouse as computer mouseviene tracciata in una variabile globale.

Il codice seguente mostra come determinare l'offset Vector2 del mouse dell'utente rispetto a un elemento GUI:


local Players = game:GetService("Players")
local CustomScrollingFrame = script.Parent
local SubFrame = CustomScrollingFrame:FindFirstChild("SubFrame")
local mouse = Players.LocalPlayer:GetMouse()
local function getPosition(X, Y)
local gui_X = CustomScrollingFrame.AbsolutePosition.X
local gui_Y = CustomScrollingFrame.AbsolutePosition.Y
local pos = Vector2.new(math.abs(X - gui_X), math.abs(Y - gui_Y - 36))
print(pos)
end
CustomScrollingFrame.MouseMoved:Connect(getPosition)

Si noti che questo evento potrebbe non essere attivato esattamente quando il mouse dell'utente entra o esce da un elemento GUI.Pertanto, gli argomenti x e y potrebbero non corrispondere perfettamente alle coordinate degli angoli della GUI or Intefaccia grafica utente.

Vedi anche

Parametri

Le coordinate dello schermo X del Topo, or mouse as computer mousein pixel, relative all'angolo superiore sinistro dello schermo.

Le coordinate dello schermo del Topo, or mouse as computer mouse Y in pixel, relative all'angolo superiore sinistro dello schermo.


MouseWheelBackward

L'evento WheelBackward si attiva quando un utente fa scorrere la ruota del mouse indietro quando il mouse è sopra un elemento GuiObject .È simile a Mouse.WheelBackward , che si attiva indipendentemente se il mouse dell'utente è su un elemento GUI.

Questo evento si attiva semplicemente come indicatore del movimento inverso della ruota.Questo significa che gli argomenti di coordinate del mouse x e y non cambiano come risultato di questo evento.Queste coordinate cambiano solo quando il mouse si muove, che può essere tracciato dall'evento GuiObject.MouseMoved.

Vedi anche

Parametri

Le coordinate dello schermo X del Topo, or mouse as computer mousein pixel, relative all'angolo superiore sinistro dello schermo.

Le coordinate dello schermo del Topo, or mouse as computer mouse Y in pixel, relative all'angolo superiore sinistro dello schermo.


MouseWheelForward

L'evento WheelForward si attiva quando un utente fa scorrere la ruota del mouse in avanti quando il mouse è sopra un elemento GuiObject .È simile a Mouse.WheelForward , che si attiva indipendentemente se il mouse dell'utente è su un elemento GUI.

Questo evento si attiva semplicemente come indicatore del movimento in avanti della ruota.Questo significa che gli argomenti di coordinate del mouse X e Y non cambiano come risultato di questo evento.Queste coordinate cambiano solo quando il mouse si muove, che può essere tracciato dall'evento GuiObject.MouseMoved.

Vedi anche

Parametri

Le coordinate dello schermo X del Topo, or mouse as computer mousein pixel, relative all'angolo superiore sinistro dello schermo.

La Y coordinata del Topo, or mouse as computer mousedell'utente.


SelectionGained

Questo evento si attiva quando il selettore del Gamepad inizia a concentrarsi su GuiObject .

Se vuoi controllare dal Gamepad seleziona le fermate che si concentrano sull'elemento GUI, puoi usare l'evento GuiObject.SelectionLost.

Quando una GUI ottiene il focus di selezione, anche il valore della proprietà SelectedObject cambia a quello che ottiene la selezione.Per determinare quale interfaccia grafica ha ottenuto la selezione, controlla il valore di questa Proprietà.


Campioni di codice

The following example prints a message when the user selects the object with a gamepad.

In order for this to work as expected, it must be placed in a LocalScript and a child of gui.

Handling GUI Selection Gained

local guiObject = script.Parent
local function selectionGained()
print("The user has selected this button with a gamepad.")
end
guiObject.SelectionGained:Connect(selectionGained)

SelectionLost

Questo evento si attiva quando il selettore Gamepad smette di concentrarsi sul GuiObject .

Se vuoi controllare dal Gamepad seleziona inizia a concentrarsi sull'elemento GUI, puoi usare l'evento GuiObject.SelectionGained.

Quando una GUI perde il focus di selezione, il valore della proprietà SelectionObject cambia in nil o nell'elemento GUI che guadagna il focus di selezione.Per determinare quale GUI abbia ottenuto la selezione, o se nessuna GUI è selezionata, controlla il valore di questa Proprietà.


Campioni di codice

The following example prints a message when the element has its focus lost on a gamepad.

In order for this to work as expected, it must be placed in a LocalScript and a child of gui.

Handling GUI Selection Lost

local guiObject = script.Parent
local function selectionLost()
print("The user no longer has this selected with their gamepad.")
end
guiObject.SelectionLost:Connect(selectionLost)

TouchLongPress

Questo evento si attiva dopo un breve momento in cui il giocatore tiene il dito sull'elemento UI utilizzando un Dispositivotouch-abilitato.Spara con un tavolo di Vector2 che descrive le posizioni relative dello schermo dei dita coinvolti nel gesto.Inoltre, si attiva più volte: Enum.UserInputState.Begin dopo un breve ritardo, Enum.UserInputState.Change se il giocatore muove il dito durante il gesto, e infine Enum.UserInputState.End .Il ritardo è dipendente dalla piattaforma; in Studio è un po' più lungo di un secondo.

Poiché questo evento richiede solo un dito, questo evento può essere simulato in Studio utilizzando l'emulatore e un Topo, or mouse as computer mouse.

Parametri

touchPositions: Array

Un array di Vector2 che descrive le posizioni relative dei dita coinvolti nel gesto.

A Enum.UserInputState che descrive lo stato del gesto:

  • Inizia gli incendi una volta all'inizio del gesto (dopo il breve ritardo)
  • Cambia i fuochi se il giocatore muove il dito mentre premere verso il basso
  • Spegni i fuochi alla fine del gesto quando rilasciano il dito.

Campioni di codice

This code sample allows the player to manipulate the screen position of some UI element, like a Frame, by holding down on the UI element for a brief moment. Then, the player moves their finger and releases. During the gesture the Frame is colored blue with a white outline.

Move UI Element with TouchLongPress

local frame = script.Parent
frame.Active = true
local dragging = false
local basePosition
local startTouchPosition
local borderColor3
local backgroundColor3
local function onTouchLongPress(touchPositions, state)
if state == Enum.UserInputState.Begin and not dragging then
-- Start a drag
dragging = true
basePosition = frame.Position
startTouchPosition = touchPositions[1]
-- Color the frame to indicate the drag is happening
borderColor3 = frame.BorderColor3
backgroundColor3 = frame.BackgroundColor3
frame.BorderColor3 = Color3.new(1, 1, 1) -- White
frame.BackgroundColor3 = Color3.new(0, 0, 1) -- Blue
elseif state == Enum.UserInputState.Change then
local touchPosition = touchPositions[1]
local deltaPosition =
UDim2.new(0, touchPosition.X - startTouchPosition.X, 0, touchPosition.Y - startTouchPosition.Y)
frame.Position = basePosition + deltaPosition
elseif state == Enum.UserInputState.End and dragging then
-- Stop the drag
dragging = false
frame.BorderColor3 = borderColor3
frame.BackgroundColor3 = backgroundColor3
end
end
frame.TouchLongPress:Connect(onTouchLongPress)

TouchPan

Questo evento si attiva quando il giocatore muove il dito sull'elemento UI utilizzando un Dispositivoabilitato al tatto.Spara poco prima di GuiObject.TouchSwipe sarebbe, e non spara con GuiObject.TouchTap .Questo evento è utile per consentire al giocatore di manipolare la posizione degli elementi UI sullo schermo.

Questo evento si attiva con un tavolo di Vector2 che descrive le posizioni relative dello schermo dei dita coinvolti nel gesto.Inoltre, si attiva più volte: Enum.UserInputState.Begin dopo un breve ritardo, Enum.UserInputState.Change quando il giocatore muove il dito durante il gesto, e infine con Enum.UserInputState.End .

Questo evento non può essere simulato in Studio utilizzando l'emulatore e un Topo, or mouse as computer mouse; devi avere un dispositivo reale attivato per il tocco per lanciarlo.

Parametri

touchPositions: Array

Un array Luau di Vector2 oggetti, ciascuno dei quali indica la posizione di tutti i dita coinvolti nel gesto.

totalTranslation: Vector2

Indica quanto lontano il gesto della padella è andato dal suo punto di partenza.

velocity: Vector2

Indica quanto rapidamente viene eseguito il gesto in ciascuna dimensione.

Indica il Enum.UserInputState del gesto.


Campioni di codice

This code sample is meant to be placed in a LocalScript within an inner Frame that is inside an outer Frame, or other GuiObject. It allows the player to manipulate the position of the inner frame by moving their finger on the outer frame.

Panning UI Element

local innerFrame = script.Parent
local outerFrame = innerFrame.Parent
outerFrame.BackgroundTransparency = 0.75
outerFrame.Active = true
outerFrame.Size = UDim2.new(1, 0, 1, 0)
outerFrame.Position = UDim2.new(0, 0, 0, 0)
outerFrame.AnchorPoint = Vector2.new(0, 0)
outerFrame.ClipsDescendants = true
local dragging = false
local basePosition
local function onTouchPan(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Begin and not dragging then
dragging = true
basePosition = innerFrame.Position
outerFrame.BackgroundTransparency = 0.25
elseif state == Enum.UserInputState.Change then
innerFrame.Position = basePosition + UDim2.new(0, totalTranslation.X, 0, totalTranslation.Y)
elseif state == Enum.UserInputState.End and dragging then
dragging = false
outerFrame.BackgroundTransparency = 0.75
end
end
outerFrame.TouchPan:Connect(onTouchPan)

TouchPinch

Questo evento si attiva quando il giocatore usa due dita per fare una pinza o un gesto di trazione sull'elemento UI utilizzando un Dispositivotouch abilitato.Un pinzamento accade quando due o più dita si avvicinano l'una all'altra e un trazione accade quando si muovono separate.Questo evento si attiva in concomitanza con GuiObject.TouchPan .Questo evento è utile per consentire al giocatore di manipolare la scala (dimensione) degli elementi dell'interfaccia utente sullo schermo e viene più spesso utilizzato per le funzionalità di zooming.

Questo evento si attiva con un tavolo di Vector2 che descrive le posizioni relative dello schermo dei dita coinvolti nel gesto.Inoltre, si attiva più volte: Enum.UserInputState.Begin dopo un breve ritardo, Enum.UserInputState.Change quando il giocatore muove un dito durante il gesto, e infine con Enum.UserInputState.End .Si deve notare che la scala deve essere utilizzata moltiplicativamente .

Poiché questo evento richiede almeno due dita, non è possibile simularlo in Studio utilizzando l'emulatore e un Topo, or mouse as computer mouse; devi avere un Dispositivoreale touch-enabled.

Parametri

touchPositions: Array

Un array Luau di Vector2 oggetti, ciascuno dei quali indica la posizione di tutti i dita coinvolti nel gesto di pinzatura.

scale: number

Un galleggiante che indica la differenza dall'inizio del gesto di pinza.

velocity: number

Un galleggiante che indica quanto rapidamente sta accadendo il gesto di pinzamento.

Indica il Enum.UserInputState del gesto.


Campioni di codice

This code sample is meant for a LocalScript within an inner Frame that is inside an outer Frame, or other GuiObject. It allows the player to scale the inner frame by performing a GuiObject.TouchPinch gesture on the outer frame.

Pinch/Pull Scaling

local innerFrame = script.Parent
local outerFrame = innerFrame.Parent
outerFrame.BackgroundTransparency = 0.75
outerFrame.Active = true
outerFrame.Size = UDim2.new(1, 0, 1, 0)
outerFrame.Position = UDim2.new(0, 0, 0, 0)
outerFrame.AnchorPoint = Vector2.new(0, 0)
outerFrame.ClipsDescendants = true
local dragging = false
local uiScale = Instance.new("UIScale")
uiScale.Parent = innerFrame
local baseScale
local function onTouchPinch(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Begin and not dragging then
dragging = true
baseScale = uiScale.Scale
outerFrame.BackgroundTransparency = 0.25
elseif state == Enum.UserInputState.Change then
uiScale.Scale = baseScale * scale -- Notice the multiplication here
elseif state == Enum.UserInputState.End and dragging then
dragging = false
outerFrame.BackgroundTransparency = 0.75
end
end
outerFrame.TouchPinch:Connect(onTouchPinch)

TouchRotate

Questo evento si attiva quando il giocatore usa due dita per fare una pinza o un gesto di trazione sull'elemento UI utilizzando un Dispositivotouch abilitato.La rotazione si verifica quando l'angolo della linea tra due dita cambia.Questo evento si attiva in concomitanza con GuiObject.TouchPan .Questo evento è utile per consentire al giocatore di manipolare la rotazione degli elementi UI sullo schermo.

Questo evento si attiva con un tavolo di Vector2 che descrive le posizioni relative dello schermo dei dita coinvolti nel gesto.Inoltre, si attiva più volte: Enum.UserInputState.Begin dopo un breve ritardo, Enum.UserInputState.Change quando il giocatore muove un dito durante il gesto, e infine con Enum.UserInputState.End .

Poiché questo evento richiede almeno due dita, non è possibile essere simulato in Studio utilizzando l'emulatore e un Topo, or mouse as computer mouse; devi avere un Dispositivoreale touch-enabled.

Parametri

touchPositions: Array

Un array Luau di Vector2 oggetti, ciascuno dei quali indica la posizione di tutti i dita coinvolti nel gesto.

rotation: number

Un galleggiante che indica quanto la rotazione sia partita dall'inizio del gesto.

velocity: number

Un galleggiante che indica quanto rapidamente viene eseguito il gesto.

Indica il Enum.UserInputState del gesto.


Campioni di codice

This code sample is meant for a LocalScript within an inner Frame that is inside an outer Frame, or other GuiObject. It allows the player to rotate the inner frame by performing a GuiObject.TouchRotate gesture on the outer frame.

Touch Rotation

local innerFrame = script.Parent
local outerFrame = innerFrame.Parent
outerFrame.BackgroundTransparency = 0.75
outerFrame.Active = true
outerFrame.Size = UDim2.new(1, 0, 1, 0)
outerFrame.Position = UDim2.new(0, 0, 0, 0)
outerFrame.AnchorPoint = Vector2.new(0, 0)
outerFrame.ClipsDescendants = true
local dragging = false
local baseRotation = innerFrame.Rotation
local function onTouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Begin and not dragging then
dragging = true
baseRotation = innerFrame.Rotation
outerFrame.BackgroundTransparency = 0.25
elseif state == Enum.UserInputState.Change then
innerFrame.Rotation = baseRotation + rotation
elseif state == Enum.UserInputState.End and dragging then
dragging = false
outerFrame.BackgroundTransparency = 0.75
end
end
outerFrame.TouchRotate:Connect(onTouchRotate)

TouchSwipe

Questo evento si attiva quando il giocatore esegue una gesture di scorrimento sull'elemento UI utilizzando un Dispositivotouch-enabled.Spara con la direzione del gesto (Su, Giù, Sinistra o Destra) e il numero di punti di contatto coinvolti nel gesto.I gesti di scorrimento vengono spesso utilizzati per modificare le schede nelle interfacce mobili.

Poiché questo evento richiede solo un dito, può essere simulato in Studio utilizzando l'emulatore e un Topo, or mouse as computer mouse.

Parametri

swipeDirection: Enum.SwipeDirection

Un Enum.SwipeDirection che indica la direzione del gesto di scorrimento (Su, Giù, Sinistra o Destra).

numberOfTouches: number

Il numero di punti di contatto coinvolti nel gesto (solitamente 1).


Campioni di codice

This code sample will cause a Frame (or other GuiObject) to bounce when a swipe gesture is performed on a touch-enabled device (or Studio's emulator). Horizontal swipes will change the hue of the GuiObject.BackgroundColor3, while vertical swipes will change the saturation.

Bouncing Color Picker

local frame = script.Parent
frame.Active = true
-- How far the frame should bounce on a successful swipe
local BOUNCE_DISTANCE = 50
-- Current state of the frame
local basePosition = frame.Position
local hue = 0
local saturation = 128
local function updateColor()
frame.BackgroundColor3 = Color3.fromHSV(hue / 256, saturation / 256, 1)
end
local function onTouchSwipe(swipeDir, _touchCount)
-- Change the BackgroundColor3 based on the swipe direction
local deltaPos
if swipeDir == Enum.SwipeDirection.Right then
deltaPos = UDim2.new(0, BOUNCE_DISTANCE, 0, 0)
hue = (hue + 16) % 255
elseif swipeDir == Enum.SwipeDirection.Left then
deltaPos = UDim2.new(0, -BOUNCE_DISTANCE, 0, 0)
hue = (hue - 16) % 255
elseif swipeDir == Enum.SwipeDirection.Up then
deltaPos = UDim2.new(0, 0, 0, -BOUNCE_DISTANCE)
saturation = (saturation + 16) % 255
elseif swipeDir == Enum.SwipeDirection.Down then
deltaPos = UDim2.new(0, 0, 0, BOUNCE_DISTANCE)
saturation = (saturation - 16) % 255
else
deltaPos = UDim2.new()
end
-- Update the color and bounce the frame a little
updateColor()
frame.Position = basePosition + deltaPos
frame:TweenPosition(basePosition, Enum.EasingDirection.Out, Enum.EasingStyle.Bounce, 0.7, true)
end
frame.TouchSwipe:Connect(onTouchSwipe)
updateColor()

TouchTap

Questo evento si attiva quando il giocatore esegue una gesture di tocco sull'elemento UI utilizzando un Dispositivotouch-enabled.Un tap è un rapido tocco singolo senza alcun movimento coinvolto (un tocco più lungo avrebbe sparato GuiObject.TouchLongPress , e muoversi durante il tocco avrebbe sparato GuiObject.TouchPan e/o GuiObject.TouchSwipe ).Spara con un tavolo di Vector2 oggetti che descrivono le posizioni relative dei dita coinvolti nel gesto.

Poiché questo evento richiede solo un dito, può essere simulato in Studio utilizzando l'emulatore e un Topo, or mouse as computer mouse.

Parametri

touchPositions: Array

Un array di Vector2 che descrive le posizioni relative dei dita coinvolti nel gesto.


Campioni di codice

This code sample will toggle the GuiObject.BackgroundTransparency of a UI element, like a Frame, when it is tapped on a touch-enabled device.

Tap Transparency Toggle

local frame = script.Parent
frame.Active = true
local function onTouchTap()
-- Toggle background transparency
if frame.BackgroundTransparency > 0 then
frame.BackgroundTransparency = 0
else
frame.BackgroundTransparency = 0.75
end
end
frame.TouchTap:Connect(onTouchTap)