GuiObject

Mostrar obsoleto

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

No creable
No explorable

GuiObject es una clase abstracta (mucho como BasePart ) para un objeto de interfaz de usuario 2D.Define todas las propiedades relacionadas con la visualización de un objeto de interfaz gráfica de usuario (Interfaz gráfica (o GUI)), como Size y Position.También tiene algunas propiedades útiles de solo lectura como AbsolutePosition , AbsoluteSize y AbsoluteRotation .

Para manipular el diseño de objetos GUI de manera especial, puedes usar una estructura de diseño como lista/flex o cuadrícula , y puedes estilarlos más allá de sus propiedades principales a través de modificadores de apariencia .

Aunque es posible detectar eventos de botones de ratón en cualquier objeto GUI usando InputBegan y InputEnded, solo ImageButton y TextButton tienen eventos convenientes dedicados como Activated para detectar clics/presiones.

Resumen

Propiedades

Propiedades heredados de GuiBase2d

Métodos

Eventos

Eventos heredados de GuiBase2d

Propiedades

Active

Leer paralelo

Esta propiedad determina si el GuiObject enviará la entrada al espacio 3D, como modelos subyacentes con una clase ClickDetector como DragDetector.

Para objetos GuiButton ( ImageButton y TextButton ), esta propiedad determina si se disparan Activated fuegos ( AutoButtonColor seguirá funcionando para esos también).Los eventos InputBegan, InputChanged y InputEnded trabajan como de costumbre sin importar el valor de esta propiedad.

Muestras de código

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

Leer paralelo

Esta propiedad determina el punto de origen de un GuiObject , relativo a su tamaño absoluto.El punto de origen determina desde dónde se posiciona el elemento (a través de GuiObject.Position ) y desde el cual se expande el renderizado GuiObject.Size .

Vea aquí para diagramas ilustrados y detalles.

Muestras de código

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

Leer paralelo

Esta propiedad se usa para automatizar el tamaño de los objetos de la interfaz de usuario padre en función del tamaño de sus descendientes.Puedes usar esta propiedad para agregar dinámicamente texto y otro contenido a un objeto de interfaz de usuario en el momento de editar o ejecutar, y el tamaño se ajustará para que encaje con ese contenido.

Cuando se establece en un valor a cualquier cosa diferente de , este objeto de interfaz de usuario puede redimensionarse según su contenido hijo.

Para obtener más información sobre cómo usar esta propiedad y cómo funciona, consulte aquí.

Muestras de código

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

Leer paralelo

Esta propiedad determina el color de un fondo GuiObject (el color de relleno).Si tu elemento contiene texto, como un TextBox, TextButton o TextLabel, asegúrate de que el color de tu fondo contraste con el color del texto.

Otra propiedad que determina las propiedades visuales del fondo es GuiObject.BackgroundTransparency ; si se establece en 1, ni el fondo ni la frontera se Renderizar.

Vea también BorderColor3 .

Muestras de código

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

Leer paralelo

Esta propiedad determina la transparencia del fondo y del borde GuiObject.Sin embargo, no determina la transparencia del texto si la interfaz de usuario es un TextBox , TextButton o TextLabel ; la transparencia del texto se determina TextBox.TextTransparency , TextButton.TextTransparency y TextLabel.TextTransparency respectivamente.

Si esta propiedad se establece en 1, ni el fondo ni la frontera se renderizarán y el fondo de la interfaz de usuario será completamente transparente.

BorderColor3

Leer paralelo

Determina el color del borde rectangular GuiObject (también conocido como el color del trazado).Esto se separa del GuiObject.BackgroundColor3 del objeto.No podrás ver el borde del objeto si su propiedad GuiObject.BorderSizePixel está configurada como 0.

Tenga en cuenta que el componente UIStroke permite efectos de borde más avanzados.

Muestras de código

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

Leer paralelo

Esta propiedad determina de qué manera se coloca el borde GuiObject relativo a sus dimensiones usando el enumerado del mismo nombre, Enum.BorderMode .

Tenga en cuenta que UIStroke puede anular esta propiedad y permitir efectos de borde más avanzados.

BorderSizePixel

Leer paralelo

Esta propiedad determina qué tan ancho se renderiza el borde GuiObject, en píxeles. Establecer esto en 0 desactiva el borde por completo.

Tenga en cuenta que UIStroke puede anular esta propiedad y permitir efectos de borde más avanzados.

Muestras de código

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

Leer paralelo

Esta propiedad determina si el GuiObject recortará (hará invisible) cualquier porción de elementos de interfaz gráfica descendientes que de lo contrario se renderizarían fuera de los límites del rectángulo.

Tenga en cuenta que Rotation no es compatible con esta propiedad.Si esta o cualquier GUI ancestral tiene un no cero , esta propiedad se ignora y los elementos GUI descendientes se renderizarán independientemente del valor de esta propiedad.

Solo lectura
No replicado
Leer paralelo

Cuando el dedo del jugador se toca y se mantiene en el GuiObject, el GuiState de la GuiObject se establecerá en Press .Del mismo modo, cuando el dedo del jugador se libere de la GuiObject , el GuiState de la GuiObject se establecerá en Idle , y cuando se desactive Interactable en el GuiObject , el Class.GuiState de la GuiObject se establecerá en NonInteractable .

Interactable

Leer paralelo

Determina si el GuiButton se puede interactuar o no, o si el GuiState del GuiObject está cambiando o no.

En un GuiButton :

En un GuiObject :

LayoutOrder

Leer paralelo

Esta propiedad controla el orden de clasificación del GuiObject al usar un UIGridStyleLayout (como UIListLayout o UIPageLayout ) con SortOrder establecido a Enum.SortOrder.LayoutOrder .No tiene funcionalidad si el objeto no tiene una estructura de interfaz de usuario hermana.

GuiObjects se ordenan en orden ascendente donde los valores más bajos tienen prioridad sobre los valores más altos.Los objetos con valores iguales vuelven a la orden en la que se agregaron.

Si no está seguro de si necesitará agregar un elemento entre dos elementos existentes en el futuro, es una buena práctica usar múltiples de 100 (0 , 100 , 200 , etc.).Esto garantiza un gran espacio de valores de orden de diseño que puedes usar para elementos ordenados entre otros elementos.

Vea también que determina el orden de renderizado del objeto en lugar de ordenar el orden.

NextSelectionDown

Leer paralelo

Esta propiedad establece el GuiObject seleccionado cuando el usuario mueve el seleccionador de gamepad hacia abajo.Si esta propiedad está vacía, mover el gamepad hacia abajo no cambiará la Interfaz gráfica (o GUI)seleccionada.

Mover el selector del gamepad hacia abajo establece el GuiService.SelectedObject a este objeto a menos que la interfaz gráfica no sea Selectable .Tenga en cuenta que esta propiedad se puede establecer en un elemento GUI incluso si no es Selectable, por lo que debe asegurarse de que el valor de una propiedad seleccionable de Interfaz gráfica (o GUI)coincida con su comportamiento esperado.

Vea también NextSelectionUp , NextSelectionLeft , y NextSelectionRight .

Muestras de código

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

Leer paralelo

Esta propiedad establece el GuiObject seleccionado cuando el usuario mueve el seleccionador de gamepad a la izquierda.Si esta propiedad está vacía, mover el gamepad a la izquierda no cambiará la Interfaz gráfica (o GUI)seleccionada.

Mover el seleccionador de gamepad a la izquierda establece el GuiService.SelectedObject a este objeto a menos que la interfaz gráfica no sea Selectable .Tenga en cuenta que esta propiedad se puede establecer en un elemento GUI incluso si no es Selectable, por lo que debe asegurarse de que el valor de una propiedad seleccionable de Interfaz gráfica (o GUI)coincida con su comportamiento esperado.

Vea también NextSelectionUp , NextSelectionDown , y NextSelectionRight .

Muestras de código

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

Leer paralelo

Esta propiedad establece el GuiObject seleccionado cuando el usuario mueve el seleccionador de gamepad a la derecha.Si esta propiedad está vacía, mover el gamepad a la derecha no cambiará la Interfaz gráfica (o GUI)seleccionada.

Mover el seleccionador de gamepad a la derecha establece el GuiService.SelectedObject a este objeto a menos que la interfaz gráfica no sea Selectable .Tenga en cuenta que esta propiedad se puede establecer en un elemento GUI incluso si no es Selectable, por lo que debe asegurarse de que el valor de una propiedad seleccionable de Interfaz gráfica (o GUI)coincida con su comportamiento esperado.

Vea también NextSelectionUp , NextSelectionDown , y NextSelectionLeft .

Muestras de código

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

Leer paralelo

Esta propiedad establece el GuiObject seleccionado cuando el usuario mueve el seleccionador de gamepad hacia arriba.Si esta propiedad está vacía, mover el gamepad hacia arriba no cambiará la Interfaz gráfica (o GUI)seleccionada.

Mover el selector de gamepad hacia arriba establece el GuiService.SelectedObject a este objeto a menos que la interfaz gráfica no sea Selectable .Tenga en cuenta que esta propiedad se puede establecer en un elemento GUI incluso si no es Selectable, por lo que debe asegurarse de que el valor de una propiedad seleccionable de Interfaz gráfica (o GUI)coincida con su comportamiento esperado.

Vea también NextSelectionDown , NextSelectionLeft , NextSelectionRight .

Muestras de código

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

Leer paralelo

Esta propiedad determina la posición GuiObject píxel y escalar usando un UDim2 . La posición se centra alrededor de la posición del objeto GuiObject.AnchorPoint .

La posición escalar es relativa al tamaño del elemento GUI padre, si es que existe.

Las porciones de píxeles del valor UDim2 son iguales independientemente del tamaño de la Interfaz gráfica (o GUI)padre.Los valores representan la posición del objeto en píxeles.La posición real de píxeles de un objeto se puede leer de la propiedad GuiBase2d.AbsolutePosition.

Rotation

Leer paralelo

Esta propiedad determina el número de grados por los cuales se gira el GuiObject .La rotación es relativa al centro del objeto, no al punto de rotación, lo que significa que no puedes cambiar el punto de rotación.Además, esta propiedad no es compatible con ClipsDescendants .

Selectable

Leer paralelo

Esta propiedad determina si la GuiObject se puede seleccionar al navegar por las interfaces gráficas usando un controlador para juego.

Si esta propiedad es true, se puede seleccionar una interfaz gráfica de usuario. Seleccionar una interfaz gráfica de usuario también establece la propiedad GuiService.SelectedObject a ese objeto.

Cuando esto es false, la interfaz gráfica no se puede seleccionar.Sin embargo, establecer esto en false cuando se selecciona una GUI no lo deseleccionará ni cambiará el valor de la propiedad GuiService.SelectedObject.

Añade GuiObject.SelectionGained y GuiObject.SelectionLost no disparará por el elemento. Para deseleccionar un GuiObject, debes cambiar la propiedad GuiService.SelectedObject.

Esta propiedad es útil si una interfaz gráfica se conecta a varias interfaces gráficas a través de propiedades como esta GuiObject.NextSelectionUp, GuiObject.NextSelectionDown, NextSelectionRight o NextSelectionLeft.En lugar de cambiar todas las propiedades para que el Gamepad no pueda seleccionar la Interfaz gráfica (o GUI), puedes deshabilitar su propiedad seleccionable para evitar que se seleccione temporalmente.Entonces, cuando quieras que el seleccionador de gamepad pueda seleccionar la interfaz de usuario, simplemente vuelve a habilitar su propiedad seleccionable.

Muestras de código

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

Leer paralelo

Esta propiedad anula el adorno de selección predeterminado utilizado para los gamepads.

Tenga en cuenta que el recubrimiento elegido SelectionImageObject superpone el recubrimiento seleccionado GuiObject con el Size de la imagen.Para obtener los mejores resultados, debe escalar el personalizado SelectionImageObject a través de los valores de escala UDim2 para ayudar a garantizar que el objeto se escala correctamente sobre el elemento seleccionado.

Cambiar el SelectionImageObject por un elemento GuiObject solo afecta ese elemento. Para afectar todos los elementos de la interfaz gráfica del usuario, establece la propiedad PlayerGui.SelectionImageObject.

Para determinar o establecer qué elemento de interfaz de usuario se selecciona por el usuario, puedes usar la propiedad GuiService.SelectedObject.El jugador usa el gamepad para seleccionar diferentes elementos de interfaz de usuario, invocando los eventos NextSelectionUp, NextSelectionDown, NextSelectionLeft y NextSelectionRight.

SelectionOrder

Leer paralelo

Los objetos GUI con un menor orden de selección se seleccionan antes que los objetos GUI con un mayor orden de selección al iniciar la selección del gamepad o llamar GuiService:Select() a un antecesor.Esta propiedad no afecta la navegación direccional.El valor predeterminado es 0.

Size

Leer paralelo

Esta propiedad determina el tamaño escalar y píxel de GuiObject usando un UDim2.

El tamaño escalar es relativo al tamaño del elemento GUI padre, si lo hay.

Las porciones de píxeles del valor UDim2 son iguales independientemente del tamaño de la Interfaz gráfica (o GUI)padre.Los valores representan el tamaño del objeto en píxeles.El tamaño de píxel actual de un objeto se puede leer de la propiedad GuiBase2d.AbsoluteSize.

Si el GuiObject tiene un padre, su tamaño en cada eje también se ve influenciado por el tamaño del padre SizeConstraint.

Muestras de código

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

Leer paralelo

Esta propiedad establece los ejes Size que el GuiObject se basará, en relación con el tamaño de su padre.

Esta propiedad es útil para crear objetos GUI que se destinan a escalar con el ancho o la altura de un objeto padre, pero no ambos, preservando efectivamente la relación de aspecto del objeto.

Transparency

Oculto
No replicado
Leer paralelo

Una propiedad mixta de BackgroundTransparency y TextTransparency.

Visible

Leer paralelo

Esta propiedad, ya sea que la GuiObject y sus descendientes se renderizarán.

La renderización de componentes individuales de un GuiObject se puede controlar individualmente a través de propiedades de transparencia como GuiObject.BackgroundTransparency , TextLabel.TextTransparency y ImageLabel.ImageTransparency .

Cuando esta propiedad es false , la GuiObject se ignorará por las estructuras de diseño como UIListLayout , UIGridLayout y UITableLayout .En otras palabras, el espacio que el elemento de otro modo ocuparía en el diseño es utilizado por otros elementos en su lugar.

Muestras de código

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

Leer paralelo

Esta propiedad determina el orden en que un GuiObject renderiza en relación con los demás.

Por defecto, renderiza en orden ascendente de prioridad donde aquellos con valores más bajos se renderizan bajo aquellos con valores más altos.Puedes cambiar el orden de renderizado dentro de un ScreenGui, SurfaceGui o BillboardGui cambiando el valor de su ZIndexBehavior .

Si no está seguro de si necesitará agregar un elemento entre dos elementos existentes en el futuro, es una buena práctica usar múltiples de 100 (0 , 100 , 200 , etc.).Esto garantiza una gran brecha de valores de orden de renderizado que puedes usar para elementos superpuestos entre otros elementos.

Vea también LayoutOrder que controla el orden de clasificación de un GuiObject cuando se usa con una estructura de diseño como UIListLayout o UIGridLayout .

Métodos

TweenPosition

Mueve suavemente una GUI a una nueva posición UDim2 en el tiempo especificado usando el especificado Enum.EasingDirection y Enum.EasingStyle.

Esta función devolverá si el preadolescente jugará.No se reproducirá si otro preadolescente está actuando en el GuiObject y el parámetro de anulación es false .

Vea también GuiObject:TweenSize() y GuiObject:TweenSizeAndPosition() .

Parámetros

endPosition: UDim2

A dónde debe moverse la interfaz gráfica.

Valor predeterminado: ""
easingDirection: Enum.EasingDirection

La dirección en la que facilitar la interfaz de usuario al final de la posición endPosition.

Valor predeterminado: "Out"
easingStyle: Enum.EasingStyle

El estilo en el que facilitar la interfaz de usuario al final de la posición endPosition.

Valor predeterminado: "Quad"
time: number

Cuánto tiempo, en segundos, debería tomar el preadolescente para completarse.

Valor predeterminado: 1
override: boolean

Si el preadolescente anulará un intermediación/interpolación de movimientoen curso.

Valor predeterminado: false
callback: function

Una función de llamada de devolución para ejecutarse cuando el preadolescente se complete.

Valor predeterminado: "nil"

Devuelve

Si el preadolescente jugará.

Muestras de código

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

Redimensiona suavemente un GuiObject a un nuevo UDim2 en el tiempo especificado usando el especificado Enum.EasingDirection y Enum.EasingStyle.

Esta función devolverá si el preadolescente jugará.Normalmente, esto siempre devolverá true , pero devolverá false si otro adolescente está activo y el anulado se establece en false .

Vea también GuiObject:TweenSize() y GuiObject:TweenSizeAndPosition() .

Parámetros

endSize: UDim2

El tamaño que debe redimensionarel GUI.

Valor predeterminado: ""
easingDirection: Enum.EasingDirection

La dirección en la que aliviar la GUI al tamaño final endSize.

Valor predeterminado: "Out"
easingStyle: Enum.EasingStyle

El estilo en el que facilitar la interfaz de usuario al tamaño final.

Valor predeterminado: "Quad"
time: number

Cuánto tiempo, en segundos, debería tomar el preadolescente para completarse.

Valor predeterminado: 1
override: boolean

Si el preadolescente anulará un intermediación/interpolación de movimientoen curso.

Valor predeterminado: false
callback: function

Una función de llamada de devolución para ejecutarse cuando el preadolescente se complete.

Valor predeterminado: "nil"

Devuelve

Si el preadolescente jugará.

Muestras de código

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

Redimensiona y mueve suavemente una interfaz de usuario a un nuevo tamaño y posición en el tiempo especificado usando el especificado y .

Esta función devolverá si el preadolescente jugará.Normalmente, esto siempre devolverá true , pero devolverá false si otro adolescente está activo y el anulado se establece en false .

Vea también GuiObject:TweenSize() y GuiObject:TweenSizeAndPosition() .

Parámetros

endSize: UDim2

El tamaño que debe redimensionarel GUI.

Valor predeterminado: ""
endPosition: UDim2

A dónde debe moverse la interfaz gráfica.

Valor predeterminado: ""
easingDirection: Enum.EasingDirection

La dirección en la que facilitar la interfaz de usuario al tamaño final y posición final.

Valor predeterminado: "Out"
easingStyle: Enum.EasingStyle

El estilo en el que facilitar la interfaz de usuario al tamaño final y posición final.

Valor predeterminado: "Quad"
time: number

Cuánto tiempo, en segundos, debería tomar el preadolescente para completarse.

Valor predeterminado: 1
override: boolean

Si el preadolescente anulará un intermediación/interpolación de movimientoen curso.

Valor predeterminado: false
callback: function

Una función de llamada de devolución para ejecutarse cuando el preadolescente se complete.

Valor predeterminado: "nil"

Devuelve

Si el preadolescente jugará.

Muestras de código

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))

Eventos

InputBegan

Este evento se activa cuando un usuario comienza a interactuar con el GuiObject a través de un dispositivo de interfaz humana-ordenador (botón del ratón hacia abajo, toque de inicio, botón de teclado hacia abajo, etc.).

El UserInputService tiene un evento de nombre similar que no está restringido a un elemento de interfaz de usuario específico: UserInputService.InputBegan .

Este evento siempre se disparará independientemente del estado del juego.

Vea también GuiObject.InputEnded y GuiObject.InputChanged .

Parámetros

Un InputObject , que contiene datos útiles para consultar la entrada del usuario como el type of input , state of input y screen coordinates of the input .


Muestras de código

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

Este evento se activa cuando un usuario cambia la forma en que interactúa a través de un dispositivo de interfaz humana-ordenador (botón del ratón hacia abajo, toque de inicio, botón de teclado hacia abajo, etc.).

El UserInputService tiene un evento de nombre similar que no está restringido a un elemento de interfaz de usuario específico: UserInputService.InputChanged .

Este evento siempre se disparará independientemente del estado del juego.

Vea también GuiObject.InputBegan y GuiObject.InputEnded .

Parámetros

Un InputObject , que contiene datos útiles para consultar la entrada del usuario como el type of input , state of input y screen coordinates of the input .


Muestras de código

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

El evento InputEnded se activa cuando un usuario deja de interactuar a través de un dispositivo de interfaz humana-ordenador (botón del ratón hacia abajo, toque de inicio, botón de teclado hacia abajo, etc.).

El UserInputService tiene un evento de nombre similar que no está restringido a un elemento de interfaz de usuario específico: UserInputService.InputEnded .

Este evento siempre se disparará independientemente del estado del juego.

Vea también GuiObject.InputBegan y GuiObject.InputChanged .

Parámetros

Un InputObject , que contiene datos útiles para consultar la entrada del usuario como el Enum.UserInputType , Enum.UserInputState y InputObject.Position .


Muestras de código

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

El evento MouseEnter se activa cuando un usuario mueve el mouse a un elemento GuiObject.

Por favor, no confíe en los argumentos x y y pasados por este evento como una forma infalible de determinar dónde está el mouse del usuario cuando entra en una Interfaz gráfica (o GUI).Estas coordenadas pueden variar incluso cuando el ratón ingresa a la interfaz gráfica a través del mismo borde - particularmente cuando el ratón ingresa al elemento rápidamente.Esto se debe al hecho de que las coordenadas indican la posición del mouse cuando se activa el evento en lugar del momento exacto en que el mouse entra en la Interfaz gráfica (o GUI).

Este evento se activa incluso cuando el elemento GUI se renderiza debajo de otro elemento.

Si desea rastrear cuando el mouse de un usuario deja un elemento de interfaz gráfica, puede usar el evento GuiObject.MouseLeave.

Ver también

Parámetros

La coordenada de la pantalla de la ratón X en píxeles, relativa a la esquina superior izquierda de la pantalla.

La coordenada de la pantalla del ratón Y en píxeles, relativa a la esquina superior izquierda de la pantalla.


Muestras de código

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

El evento MouseLeave se activa cuando un usuario mueve el mouse fuera de un elemento GuiObject.

Por favor, no confíe en los argumentos x y y pasados por este evento como una forma infalible de determinar dónde está el mouse del usuario cuando sale de una Interfaz gráfica (o GUI).Estas coordenadas pueden variar incluso cuando el mouse abandona la interfaz gráfica a través del mismo borde - particularmente cuando el mouse abandona el elemento rápidamente.Esto se debe al hecho de que las coordenadas indican la posición del mouse cuando se activa el evento en lugar del momento exacto en que el mouse deja la Interfaz gráfica (o GUI).

Este evento se activa incluso cuando el elemento GUI se renderiza debajo de otro elemento.

Ver también

Parámetros

La coordenada de la pantalla de la ratón X en píxeles, relativa a la esquina superior izquierda de la pantalla.

La coordenada de la pantalla del ratón Y en píxeles, relativa a la esquina superior izquierda de la pantalla.


MouseMoved

Se activa cada vez que un usuario mueve el mouse mientras está dentro de un elemento GuiObject .Es similar a Mouse.Move , que se activa independientemente de si el mouse del usuario está sobre un elemento de interfaz gráfica.

Nota, este evento se activa cuando se actualiza la posición del ratón, por lo tanto, se activará repetidamente mientras se mueve.

Los argumentos x y y indican las coordenadas de la pantalla actualizadas del mouse del usuario en píxeles.Estos pueden ser útiles para determinar la ubicación del ratónen la Interfaz gráfica (o GUI), la pantalla y el delta desde la posición anterior del ratónsi se está rastreando en una variable global.

El código a continuación muestra cómo determinar el desplazamiento Vector2 del mouse del usuario relativo a un elemento de interfaz gráfica:


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)

Tenga en cuenta que este evento puede no disparar exactamente cuando el mouse del usuario ingresa o sale de un elemento de interfaz gráfica.Por lo tanto, los argumentos x y y pueden no coincidir perfectamente con las coordenadas de los bordes de la Interfaz gráfica (o GUI).

Ver también

Parámetros

La coordenada de la pantalla de la ratón X en píxeles, relativa a la esquina superior izquierda de la pantalla.

La coordenada de la pantalla del ratón Y en píxeles, relativa a la esquina superior izquierda de la pantalla.


MouseWheelBackward

El evento WheelBackward se activa cuando un usuario desplaza la rueda del ratón hacia atrás cuando el ratón está sobre un elemento GuiObject.Es similar a Mouse.WheelBackward , que se activa independientemente de si el mouse del usuario está sobre un elemento de interfaz gráfica.

Este evento se dispara simplemente como un indicador del movimiento hacia atrás de la rueda.Esto significa que los argumentos de coordenadas del ratón x y y no cambian como resultado de este evento.Estas coordenadas solo cambian cuando el mouse se mueve, lo que se puede rastrear por el evento GuiObject.MouseMoved.

Ver también

Parámetros

La coordenada de la pantalla de la ratón X en píxeles, relativa a la esquina superior izquierda de la pantalla.

La coordenada de la pantalla del ratón Y en píxeles, relativa a la esquina superior izquierda de la pantalla.


MouseWheelForward

El evento WheelForward se activa cuando un usuario desplaza la rueda del ratón hacia adelante cuando el ratón está sobre un elemento GuiObject.Es similar a Mouse.WheelForward , que se activa independientemente de si el mouse del usuario está sobre un elemento de interfaz gráfica.

Este evento se dispara simplemente como un indicador del movimiento hacia adelante de la rueda.Esto significa que los argumentos de coordenadas del ratón X y Y no cambian como resultado de este evento.Estas coordenadas solo cambian cuando el mouse se mueve, lo que se puede rastrear por el evento GuiObject.MouseMoved.

Ver también

Parámetros

La coordenada de la pantalla de la ratón X en píxeles, relativa a la esquina superior izquierda de la pantalla.

La coordenada Y del ratóndel usuario.


SelectionGained

Este evento se activa cuando el seleccionador de Gamepad comienza a centrarse en el GuiObject.

Si quieres comprobar desde el Gamepad seleccionar dejar de enfocarse en el elemento GUI, puedes usar el evento GuiObject.SelectionLost.

Cuando una GUI gana el enfoque de selección, el valor de la propiedad SelectedObject también cambia a la que gana la selección.Para determinar qué GUI obtuvo la selección, verifique el valor de esta propiedad.


Muestras de código

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

Este evento se activa cuando el seleccionador de Gamepad deja de centrarse en el GuiObject.

Si quieres comprobar desde el Gamepad selecciona empieza a centrarse en el elemento de la interfaz gráfica, puedes usar el evento GuiObject.SelectionGained.

Cuando una GUI pierde el enfoque de selección, el valor de la propiedad SelectionObject cambia a nil o al elemento de la interfaz que gana el enfoque de selección.Para determinar qué GUI obtuvo la selección, o si no se selecciona ninguna GUI, compruebe el valor de esta propiedad.


Muestras de código

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

Este evento se activa después de un breve momento cuando el jugador mantiene su dedo en el elemento de la interfaz de usuario usando un dispositivo que admite táctiles.Dispara con una tabla de Vector2 que describe las posiciones relativas de la pantalla de los dedos involucrados en el gesto.Además, dispara varias veces: Enum.UserInputState.Begin después de un breve retraso, Enum.UserInputState.Change si el jugador mueve el dedo durante el gesto, y finalmente Enum.UserInputState.End .El retraso es dependiente de la plataforma; en Studio es un poco más largo que un segundo.

Dado que este evento solo requiere un dedo, este evento se puede simular en Studio usando el emulador y un ratón.

Parámetros

touchPositions: Array

Un array de que describe las posiciones relativas de los dedos involucrados en el gesto.

Un Enum.UserInputState que describe el estado del gesto:

  • Comience fuegos una vez al comienzo del gesto (después del breve retraso)
  • Cambiar fuegos si el jugador mueve el dedo mientras presiona hacia abajo
  • Apaga los fuegos una vez al final del gesto cuando sueltan su dedo.

Muestras de código

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

Este evento se activa cuando el jugador mueve el dedo en el elemento de la interfaz de usuario usando un dispositivo habilitado para el tacto.Dispara poco antes de que GuiObject.TouchSwipe dispararía, y no dispara con GuiObject.TouchTap.Este evento es útil para permitir que el jugador manipule la posición de los elementos de la interfaz en la pantalla.

Este evento se activa con una tabla de Vector2 que describe las posiciones relativas de la pantalla de los dedos involucrados en el gesto.Además, dispara varias veces: Enum.UserInputState.Begin después de un breve retraso, Enum.UserInputState.Change cuando el jugador mueve el dedo durante el gesto, y finalmente con Enum.UserInputState.End .

Este evento no se puede simular en Studio usando el emulador y un ratón; debe tener un dispositivo real habilitado para tocar para dispararlo.

Parámetros

touchPositions: Array

Un array de Luau de Vector2 objetos, cada uno que indica la posición de todos los dedos involucrados en el gesto.

totalTranslation: Vector2

Indica hasta dónde se ha movido el gesto de la sartén desde su punto de partida.

velocity: Vector2

Indica con qué rapidez se está realizando el gesto en cada dimensión.

Indica el Enum.UserInputState de la gestión.


Muestras de código

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

Este evento se activa cuando el jugador usa dos dedos para hacer un gesto de pinzamiento o de tracción en el elemento de la interfaz de usuario usando un dispositivo habilitado para el tacto.Un pinchazo ocurre cuando dos o más dedos se mueven más cerca el uno del otro, y un empuje ocurre cuando se separan.Este evento se activa en conjunción con GuiObject.TouchPan .Este evento es útil para permitir que el jugador manipule el tamaño (tamaño) de los elementos de la interfaz de usuario en la pantalla, y se usa más a menudo para funciones de zoom.

Este evento se activa con una tabla de Vector2 que describe las posiciones relativas de la pantalla de los dedos involucrados en el gesto.Además, dispara varias veces: Enum.UserInputState.Begin después de un breve retraso, Enum.UserInputState.Change cuando el jugador mueve un dedo durante el gesto, y finalmente con Enum.UserInputState.End .Se debe tener en cuenta que la escala debe usarse multiplicativamente .

Dado que este evento requiere al menos dos dedos, no es posible simularlo en Studio usando el emulador y un ratón; debe tener un dispositivo real habilitado para tocar.

Parámetros

touchPositions: Array

Un array de Luau de Vector2 objetos, cada uno que indica la posición de todos los dedos involucrados en el gesto de presión.

scale: number

Un flotante que indica la diferencia desde el comienzo del gesto de pellizco.

velocity: number

Un flotante que indica qué tan rápido está ocurriendo el gesto de agarre.

Indica el Enum.UserInputState de la gestión.


Muestras de código

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

Este evento se activa cuando el jugador usa dos dedos para hacer un gesto de pinzamiento o de tracción en el elemento de la interfaz de usuario usando un dispositivo habilitado para el tacto.La rotación ocurre cuando el ángulo de la línea entre dos dedos cambia.Este evento se activa en conjunción con GuiObject.TouchPan .Este evento es útil para permitir que el jugador manipule la rotación de los elementos de la interfaz en la pantalla.

Este evento se activa con una tabla de Vector2 que describe las posiciones relativas de la pantalla de los dedos involucrados en el gesto.Además, dispara varias veces: Enum.UserInputState.Begin después de un breve retraso, Enum.UserInputState.Change cuando el jugador mueve un dedo durante el gesto, y finalmente con Enum.UserInputState.End .

Dado que este evento requiere al menos dos dedos, no es posible ser simulado en Studio usando el emulador y un ratón; debe tener un dispositivo real habilitado para tocar.

Parámetros

touchPositions: Array

Un array de Luau de Vector2 objetos, cada uno que indica la posición de todos los dedos involucrados en el gesto.

rotation: number

Un flotante que indica cuánto ha girado la rotación desde el comienzo del gesto.

velocity: number

Un flotante que indica qué tan rápidamente se está realizando el gesto.

Indica el Enum.UserInputState de la gestión.


Muestras de código

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

Este evento se activa cuando el jugador realiza un gesto de deslizamiento en el elemento de la interfaz de usuario usando un dispositivo habilitado para el tacto.Dispara con la dirección del gesto (Arriba, Abajo, Izquierda o Derecha) y el número de puntos de contacto involucrados en el gesto.Los gestos de deslizamiento se utilizan a menudo para cambiar las pestañas en las interfaces móviles.

Dado que este evento solo requiere un dedo, se puede simular en Studio usando el emulador y un ratón.

Parámetros

swipeDirection: Enum.SwipeDirection

Un Enum.SwipeDirection que indica la dirección del gesto de deslizamiento (Arriba, Abajo, Izquierda o Derecha).

numberOfTouches: number

El número de puntos de contacto involucrados en el gesto (normalmente 1).


Muestras de código

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

Este evento se activa cuando el jugador realiza un gesto de toque en el elemento de la interfaz de usuario usando un dispositivo habilitado para tocar.Un toque es un rápido toque sin ningún movimiento involucrado (un toque más largo dispararía GuiObject.TouchLongPress , y moverse durante el toque dispararía GuiObject.TouchPan y/o GuiObject.TouchSwipe ).Dispara con una tabla de Vector2 objetos que describen las posiciones relativas de los dedos involucrados en el gesto.

Dado que este evento solo requiere un dedo, se puede simular en Studio usando el emulador y un ratón.

Parámetros

touchPositions: Array

Un array de que describe las posiciones relativas de los dedos involucrados en el gesto.


Muestras de código

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)