GuiObject

顯示已棄用項目

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

無法建立
無法瀏覽

GuiObject 是一個抽象類 (非常像 BasePart ) 對於 2D 使用者介面對物件。它定義所有與顯示圖形用戶介面 (GUI) 對象相關的屬性,例如 SizePosition 。它也有一些有用的僅讀屬性,例如 AbsolutePosition , AbsoluteSizeAbsoluteRotation

若要以特殊方式操縱 GUI 對象的布局,您可以使用 列表/柔性網格 等布局結構,並通過 外觀修改器 為它們超出核心屬性進行格式化。

雖然使用 InputBeganInputEnded 可以在任何 GUI 對象上偵測滑鼠按鈕事件,但只有 ImageButtonTextButton 有方便的專用事件,例如 Activated 來偵測點擊/按下。

概要

屬性

屬性 繼承自 GuiBase2d

方法

活動

活動 繼承自 GuiBase2d

屬性

Active

平行讀取

此屬性決定是否會將 GuiObject 輸入傾斜到 3D 空間,例如底層模型具有 ClickDetector 類似的 DragDetector 類。

對於 物件 ( 和 ),此屬性決定是否發生火災 ( 對於這些物件也仍然有效)。事件 InputBegan , InputChangedInputEnded 無論值多少都正常運作。

範例程式碼

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

平行讀取

此屬性決定了 GuiObject 的起始點,相對於其絕對尺寸。起始點決定從哪裡元素被放置(通過 GuiObject.Position )和從哪裡渲染的 GuiObject.Size 擴展。

請見 這裡 獲得說明圖和詳情。

範例程式碼

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

平行讀取

此屬性用於自動根據子孫的大小來調整父級 UI 對象的大小。您可以使用此屬性來在編輯或運行時動態添加文字和其他內容到 UI 對象,並且尺寸會調整以適應該內容。

當 設為 值以外的任何東西時,此 UI 對象可能會根據其子內容進行縮放。

有關如何使用此屬性以及它如何運作的更多信息,請參閱 這裡

範例程式碼

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

平行讀取

此屬性決定了 GuiObject 背景的顏色 (填充顏色)。如果你的元素包含文字,例如 TextBox , TextButtonTextLabel , 請確保背景顏色與文字顏色對比。

決定背景視覺特性的另一個屬性是 GuiObject.BackgroundTransparency;如果將其設為 1,背景和邊界都不會成像。

也見 BorderColor3

範例程式碼

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

平行讀取

此屬性決定了 GuiObject 背景和邊緣的透明度。它不會決定文字透明度,如果 GUI 是 TextBox , TextButtonTextLabel ; 文字透明度是由 TextBox.TextTransparency , TextButton.TextTransparencyTextLabel.TextTransparency 決定的。

如果此屬性設為 1,背景和邊框將不會渲染,使用者介面背景將完全透明。

BorderColor3

平行讀取

決定 GuiObject 長方形邊框的顏色 (也稱為線條顏色)。這與對物件的 GuiObject.BackgroundColor3 是分開的。如果其 GuiObject.BorderSizePixel 屬性設為 0,您將無法看到對物件的邊界。

請注意,UIStroke 組件允許更進階的邊緣效果。

範例程式碼

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

平行讀取

這個屬性決定以什麼方式將 GuiObject 邊框放置在相對於其尺寸的枚舉中,Enum.BorderMode

請注意,UIStroke 可以覆蓋此屬性並允許更進階的邊緣效果。

BorderSizePixel

平行讀取

這個屬性決定了 GuiObject 邊框渲染的寬度,以畫素為單位。將其設為 0 將完全禁用邊框。

請注意,UIStroke 可以覆蓋此屬性並允許更進階的邊緣效果。

範例程式碼

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

平行讀取

此屬性決定是否會將 GuiObject 剪輯(使其隱形)任何子GUI元素的一部分,將不會在矩陣範圍之外顯示。

請注意,Rotation 不支持此屬性。如果這個或任何祖先 GUI 有 非零 ,這個屬性將被忽略,子孫 GUI 元素將無論如何渲染,無視此屬性的值。

唯讀
未複製
平行讀取

當玩家的手指被點擊並保持在 GuiObject 上時, GuiStateGuiObject 將被設置為 Press。相同地,當玩家的手指從 GuiObject 被釋放時,GuiStateGuiObject 將被設置為 Idle,當 Interactable 被關閉在 GuiObject 時,Class.GuiStateGuiObject 將被設置為 NonInteractable

Interactable

平行讀取

決定是否可以與 GuiButton 互動,或者 GuiStateGuiObject 是否正在變更。

GuiButton 上:

GuiObject 上:

LayoutOrder

平行讀取

此屬性控制使用 (例如 或 )時的排序順序,當 設為 時。如果對象沒有兄弟 UI 布局結構,就沒有功能。

GuiObjects 在上升的順序中排序,低值優先於高值。具有相同值的對象會回到它們被添加的順序。

如果您不確定未來是否需要在兩個現有元素之間添加元素,那麼使用 100 ( 0 , 100 , 200 ,等) 的倍數是一個很好的習慣。這樣可以確保間隔大的布局順序值,可用於在其他元素之間訂購的元素。

也參見 ZIndex ,這會決定對物件的 渲染順序 而不是排序順序。

NextSelectionDown

平行讀取

此屬性設置在使用者向下移動遊戲控制器選擇器時所選擇的 屬性。如果此屬性為空,將遊戲手柄向下移動不會更改選擇的 GUI。

將遊戲控制器選擇器向下移動設置 GuiService.SelectedObject 到此對象,除非 GUI 不是 Selectable 。請注意,此屬性可以設為 GUI 元素,即使它不是 Selectable ,因此您應該確保 GUI 的可選擇屬性值與預期的行為匹配。

也見 NextSelectionUp , NextSelectionLeft , 及 NextSelectionRight .

範例程式碼

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

平行讀取

此屬性設置在使用者將遊戲控制器選擇器移到左側時選擇的 屬性。如果此屬性為空,將遊戲手柄移到左側不會更改選擇的 GUI。

將遊戲控制器選擇器移到左側將設置 GuiService.SelectedObject 為此對象,除非 GUI 不是 Selectable 。請注意,此屬性可以設為 GUI 元素,即使它不是 Selectable ,因此您應該確保 GUI 的可選擇屬性值與預期的行為匹配。

也見 NextSelectionUp , NextSelectionDown , 及 NextSelectionRight .

範例程式碼

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

平行讀取

此屬性設置在使用者將 GuiObject 選擇器移到右側時選擇的 。如果此屬性為空,將遊戲手柄移動到右側不會更改選擇的 GUI。

將遊戲控制器選擇器移動到右側將設置 GuiService.SelectedObject 到此對象,除非 GUI 不是 Selectable 。請注意,此屬性可以設為 GUI 元素,即使它不是 Selectable ,因此您應該確保 GUI 的可選擇屬性值與預期的行為匹配。

也見 NextSelectionUp , NextSelectionDown , 及 NextSelectionLeft .

範例程式碼

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

平行讀取

此屬性設置在使用者移動遊戲控制器選擇器向上時選擇的 屬性。如果此屬性為空,將遊戲手柄向上移動不會更改選擇的 GUI。

將遊戲控制器選擇器向上移動設置 GuiService.SelectedObject 到此對象,除非 GUI 不是 Selectable 。請注意,此屬性可以設為 GUI 元素,即使它不是 Selectable ,因此您應該確保 GUI 的可選擇屬性值與預期的行為匹配。

也見 NextSelectionDown , NextSelectionLeft , NextSelectionRight .

範例程式碼

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

平行讀取

此屬性使用 決定像素和Scalar位置。位置是關於對物件的 中心。

Scalar位置是相對於父GUI元素的大小,如果有。

UDim2的像素部分無論父GUI的大小如何都相同。值代表物件在畫素上的位置。物件的實際像素位置可以從 GuiBase2d.AbsolutePosition 屬性中讀取。

Rotation

平行讀取

此屬性決定 GuiObject 旋轉的度數。旋轉是相對於對物件的 中心 的, 不是AnchorPoint,意味著您無法更改旋轉點。此外,此屬性不兼容 ClipsDescendants

Selectable

平行讀取

此屬性決定是否在使用遊戲控制器導航時選擇 GuiObject 儀表板。

如果此屬性是 true ,可以選擇 GUI。選擇 GUI 也會將 GuiService.SelectedObject 屬性設置為該物件。

當這是 false 時,無法選擇 GUI 。然而,將此設為 false 當使用 GUI 時,將不會卸下它或更改 GuiService.SelectedObject 屬性的值。

添加 GuiObject.SelectionGainedGuiObject.SelectionLost 不會為元素發射。要取消選擇 GuiObject,您必須更改 GuiService.SelectedObject 屬性。

這個屬性有用如果GUI通過屬性,例如這個GuiObject.NextSelectionUpGuiObject.NextSelectionDownNextSelectionRightNextSelectionLeft連接到多個GUI。而不是改變所有的屬性,使遊戲手柄無法選擇 GUI,您可以暫時禁用其可選屬性,以防止它被選擇。然後,當您想要遊戲控制器能夠選擇 GUI 時,只需重新啟用其可選擇的屬性即可。

範例程式碼

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

平行讀取

此屬性覆蓋了用於遊戲板的預設選擇裝飾。

請注意,選擇的 SelectionImageObject 覆蓋了選擇的 GuiObject 以圖像的 Size 。為了獲得最佳效果,您應該通過比例 SelectionImageObject 值將自訂 UDim2 縮放到選定的元素上,以幫助確保對象正確縮放。

變更 SelectionImageObject 對於 GuiObject 元素只會影響該元素。若要影響使用者所有的 GUI 元素,請設置 PlayerGui.SelectionImageObject 屬性。

若要確定使用者選擇哪個 GUI 元素,您可以使用 GuiService.SelectedObject 屬性。玩家使用遊戲手柄選擇不同的 GUI 元素,召喚 NextSelectionUp , NextSelectionDown , NextSelectionLeftNextSelectionRight 事件。

SelectionOrder

平行讀取

具有較低選擇順序的 GuiObject 在開始遊戲控制器選擇或呼叫祖先 GuiService:Select() 時,會先選擇具有較低選擇順序的 GuiObject 而不是具有較高選擇順序的 GuiObject。此屬性不會影響方向導航。預設值為 0。

Size

平行讀取

此屬性使用 GuiObject 決定Scalar和像素尺寸,使用 UDim2

Scalar 尺寸與父 GUI 元素的尺寸相對,如果有。

UDim2的像素部分無論父GUI的大小如何都相同。值代表物件的像素大小。對象的實際像素尺寸可以從 GuiBase2d.AbsoluteSize 屬性中讀取。

如果 GuiObject 有一個父元素,其各軸的尺寸也會受到父父元素的 SizeConstraint 影響。

範例程式碼

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

平行讀取

此屬性設置 Size 軸,將基於父父元素的大小對應地對 GuiObject 進行調整。

此屬性對於創建用於擴展到父對物件寬度 高度的圖形用戶介面對象有用,但不僅限於兩者,有效保留對物件的比例。

Transparency

隱藏
未複製
平行讀取

混合屬性 BackgroundTransparencyTextTransparency

Visible

平行讀取

這個屬性是否 GuiObject 和其子孫將被渲染。

GuiObject 的個別組件的渲染可以通過透明度屬性,例如 GuiObject.BackgroundTransparencyTextLabel.TextTransparencyImageLabel.ImageTransparency 進行獨立控制。

當此屬性為 false 時,GuiObject將被忽略布局結構,例如UIListLayoutUIGridLayoutUITableLayout。換言之,元素通常會在布局中佔用的空間,會被其他元素取代。

範例程式碼

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

平行讀取

此屬性決定 GuiObject 對其他人的渲染順序。

預設情況下,GuiObjects 在遞增的優先級順序中渲染,那些擁有更低ZIndex 值的人被渲染在那些擁有更高值的人之下。您可以在 ScreenGuiSurfaceGuiBillboardGui 內變更渲染順序,變更其 ZIndexBehavior 值。

如果您不確定未來是否需要在兩個現有元素之間添加元素,那麼使用 100 ( 0 , 100 , 200 ,等) 的倍數是一個很好的習慣。這樣可以確保渲染順序值之間的大差距,您可以使用它來渲染在其他元素之間層疊的元素。

也參見LayoutOrder,這控制使用布局結構,例如 **** 或GuiObject時的排序順序UIListLayoutUIGridLayout

方法

TweenPosition

使用指定的 UDim2Enum.EasingDirection 以及 Enum.EasingStyle 順利將 GUI 移到指定時間的新位置。

此功能將返回漢子是否會播玩 遊玩。如果另一個青少年正在操作 GuiObject 和覆蓋參數是 false ,將不會播放。

也見 GuiObject:TweenSize()GuiObject:TweenSizeAndPosition()

參數

endPosition: UDim2

GUI應移動到哪裡。

預設值:""
easingDirection: Enum.EasingDirection

將 GUI 移至 終端位置 的方向。

預設值:"Out"
easingStyle: Enum.EasingStyle

將 GUI 移至 結束位置 的風格。

預設值:"Quad"
time: number

青少年需要多久才能完成,以秒為單位。

預設值:1
override: boolean

青少年是否會覆蓋進行中的青少年。

預設值:false
callback: function

在青少年完成時執行的回呼函數。

預設值:"nil"

返回

青少年是否會播玩 遊玩。

範例程式碼

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

使用指定的 GuiObjectEnum.EasingStyle 將一個 UDim2 平滑地調整為新的 Enum.EasingDirection 在指定的時間。

此功能將返回漢子是否會播玩 遊玩。通常這會永遠返回true,但如果另一個青少年啟用了並將覆蓋設為false,則會返回false

也見 GuiObject:TweenSize()GuiObject:TweenSizeAndPosition()

參數

endSize: UDim2

GUI 應該調整大小的尺寸。

預設值:""
easingDirection: Enum.EasingDirection

將 GUI 向 endSize 方向調整。

預設值:"Out"
easingStyle: Enum.EasingStyle

將 GUI 調整到 結束尺寸 的風格。

預設值:"Quad"
time: number

青少年需要多久才能完成,以秒為單位。

預設值:1
override: boolean

青少年是否會覆蓋進行中的青少年。

預設值:false
callback: function

在青少年完成時執行的回呼函數。

預設值:"nil"

返回

青少年是否會播玩 遊玩。

範例程式碼

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

使用指定的 UDim2Enum.EasingDirectionEnum.EasingStyle 將 GUI 平滑地縮放到指定時間的新尺寸和位置。

此功能將返回漢子是否會播玩 遊玩。通常這會永遠返回true,但如果另一個青少年啟用了並將覆蓋設為false,則會返回false

也見 GuiObject:TweenSize()GuiObject:TweenSizeAndPosition()

參數

endSize: UDim2

GUI 應該調整大小的尺寸。

預設值:""
endPosition: UDim2

GUI應移動到哪裡。

預設值:""
easingDirection: Enum.EasingDirection

將 GUI 移至 endSizeendPosition 的方向。

預設值:"Out"
easingStyle: Enum.EasingStyle

將 GUI 調整到 endSizeendPosition 的風格。

預設值:"Quad"
time: number

青少年需要多久才能完成,以秒為單位。

預設值:1
override: boolean

青少年是否會覆蓋進行中的青少年。

預設值:false
callback: function

在青少年完成時執行的回呼函數。

預設值:"nil"

返回

青少年是否會播玩 遊玩。

範例程式碼

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

活動

InputBegan

當使用者開始與 GuiObject 通過人工智慧輸入裝置互動時,此事件會發生(例如:滑鼠按鈕向下、觸摸開始、鍵盤按鈕向下等)。

UserInputService 有相同名稱的事件,不受限於特定的使用者介面元素:UserInputService.InputBegan

此事件將無論遊戲狀態如何總是發射。

也見 GuiObject.InputEndedGuiObject.InputChanged

參數

一個 InputObject , 包含用於查詢用戶輸入的有用數據,例如 type of input , state of inputscreen coordinates of the input


範例程式碼

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

當使用者變更如何透過人工智慧與電腦介面裝置(滑鼠按鈕向下、觸摸開始、鍵盤按鈕向下等)進行互動時,此事件會發生。

UserInputService 有相同名稱的事件,不受限於特定的使用者介面元素:UserInputService.InputChanged

此事件將無論遊戲狀態如何總是發射。

也見 GuiObject.InputBeganGuiObject.InputEnded

參數

一個 InputObject , 包含用於查詢用戶輸入的有用數據,例如 type of input , state of inputscreen coordinates of the input


範例程式碼

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

輸入已結束事件會在使用者停止使用人工智慧與電腦介面裝置(滑鼠按鈕向下、觸摸開始、鍵盤按鈕向下等)互動時發生。

UserInputService 有相同名稱的事件,不受限於特定的使用者介面元素:UserInputService.InputEnded

此事件將無論遊戲狀態如何總是發射。

也見 GuiObject.InputBeganGuiObject.InputChanged

參數

一個 InputObject , 包含用於查詢用戶輸入的有用數據,例如 Enum.UserInputType , Enum.UserInputStateInputObject.Position


範例程式碼

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

當使用者將滑鼠移入 GuiObject 元素時,滑鼠進入事件發生。

請勿依賴此事件傳回的 xy 參數來確定使用者的鼠標在進入 GUI 時的位置。即使在滑鼠通過相同的邊緣進入 GUI 時,這些坐標可能會變化 - 特別是當滑鼠快速進入元素時。這是因為協調點指示的位置是事件發生時的滑鼠位置,而不是滑鼠進入 GUI 的準確時刻。

此事件即使在 GUI 元素在另一個元素下渲染時也會發生。

如果您想跟蹤用戶的鼠標何時離開 GUI 元素,您可以使用 GuiObject.MouseLeave 事件。

也見「也見」

參數

滑鼠的 X 屏幕坐標以像素為單位,相對於屏幕左上角。

滑鼠的 Y 屏幕坐標以像素為單位,相對於屏幕左上角。


範例程式碼

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

當使用者將鼠標從 GuiObject 元素移出時,滑鼠離開事件會發生。

請勿依賴這個事件傳回的 xy 參數作為確定使用者鼠標位置的絕對方式。即使在滑鼠通過相同的邊緣離開 GUI 時,這些坐標可能會變化 - 特別是當滑鼠快速離開元素時。這是因為協調點指示的位置是事件發生時的滑鼠位置,而不是滑鼠離開 GUI 的準確時刻。

此事件即使在 GUI 元素在另一個元素下渲染時也會發生。

也見「也見」

參數

滑鼠的 X 屏幕坐標以像素為單位,相對於屏幕左上角。

滑鼠的 Y 屏幕坐標以像素為單位,相對於屏幕左上角。


MouseMoved

GuiObject 元素內時,每當使用者移動滑鼠時,都會發生火災。與 Mouse.Move 相似,無論使用者的滑鼠是否在 GUI 元素上,都會發射。

注意,此事件會在滑鼠位置更新時發生,因此在移動時會重複發生。

xy 參數指示使用者鼠標的更新畫面坐標以磚格。這些可能有助於在GUI、畫面和delta上確定鼠滑鼠的位置,因為如果在全球變量中跟蹤鼠滑鼠,它的前一個位置。

下面的代碼示範如何確定使用者的滑鼠相對於 GUI 元素的偏移 Vector2


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)

請注意,此事件可能不會在使用者的鼠標進入或離開 GUI 元素時發生。因此, xy 參數可能不會完全匹配 GUI 邊緣的坐標。

也見「也見」

參數

滑鼠的 X 屏幕坐標以像素為單位,相對於屏幕左上角。

滑鼠的 Y 屏幕坐標以像素為單位,相對於屏幕左上角。


MouseWheelBackward

輪盤向後事件會在使用者將滑鼠輪向返回時發生,當滑鼠位於 GuiObject 元素上時。與 Mouse.WheelBackward 相似,無論使用者的滑鼠是否在 GUI 元素上,都會發射。

這個事件只是輪子向後移動的指標。這意味著 xy 滑鼠坐標參數不會因此事件而變更。這些坐標只會在滑鼠移動時變更,可以透過 GuiObject.MouseMoved 事件進行追蹤。

也見「也見」

參數

滑鼠的 X 屏幕坐標以像素為單位,相對於屏幕左上角。

滑鼠的 Y 屏幕坐標以像素為單位,相對於屏幕左上角。


MouseWheelForward

輪向前事件會在使用者將滑鼠輪向前移動時發生,當滑鼠位於 GuiObject 元素上時。與 Mouse.WheelForward 相似,無論使用者的滑鼠是否在 GUI 元素上,都會發射。

這個事件只是輪子前進的指標。這意味著 XY 滑鼠坐標參數在此事件發生後不會發生變化。這些坐標只會在滑鼠移動時變更,可以透過 GuiObject.MouseMoved 事件進行追蹤。

也見「也見」

參數

滑鼠的 X 屏幕坐標以像素為單位,相對於屏幕左上角。

使用者滑鼠標的 Y 坐標。


SelectionGained

此事件會在遊戲控制器選擇器開始專注於 GuiObject 時發生。

如果你想從遊戲手柄選擇停止關注 GUI 元素,你可以使用 GuiObject.SelectionLost 事件。

當 GUI 獲得選擇焦點時,SelectedObject 屬性的值也會變更為獲得選擇的值。要確定哪個 GUI 獲得選擇,請檢查此屬性的值。


範例程式碼

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

此事件會在遊戲控制器選擇器停止對 GuiObject 的焦點時發生。

如果你想從遊戲手柄選擇開始關注 GUI 元素,你可以使用 GuiObject.SelectionGained 事件。

當使用者介面失去選擇焦點時,SelectionObject 屬性值會變更為nil 或獲得選擇焦點的 GUI 元素。要確定哪個 GUI 獲得選擇,或者如果沒有選擇任何 GUI,請檢查此屬性的值。


範例程式碼

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

此事件在玩家使用觸摸啟用的裝置將手指放在介面元素上時發生短暫時間後發射。它使用描述手指相對屏幕位置的 Vector2 表發射。此外,它會多次發射:Enum.UserInputState.Begin後短暫延遲,Enum.UserInputState.Change如果玩家在姿勢期間移動手指,最後Enum.UserInputState.End。延遲是平台依賴的;在 Studio 中,它比一秒多一點。

由於此事件只需要一個手指,因此可以使用 Studio 的模擬器和滑鼠來模擬此事件。

參數

touchPositions: Array

一個由 組成的陣列,用於描述參與手勢的手指的相對位置。

一個 Enum.UserInputState 描述手勢狀態的:

  • 開始火焰一次在手勢開始時(在短暫延遲後)
  • 如果玩家在按下時移動手指,則更改火焰
  • 在他們釋放手指時,一次在動作結束時結束火焰。

範例程式碼

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

當玩家使用具有觸摸啟用的裝置移動手指到 UI 元素時,此事件會發生。它在 GuiObject.TouchSwipe 之前短時間發射,並不會與 GuiObject.TouchTap 發射。這個事件有助於允許玩家在畫面上操縱 UI 元素的位置。

這個事件發射時使用 Vector2 桌子來描述參與手勢的手指相對畫面位置。此外,它會多次發射:Enum.UserInputState.Begin在短暫延遲後,Enum.UserInputState.Change當玩家移動手指時,以及最後使用 Enum.UserInputState.End

這個事件無法在 Studio 使用模擬器和滑鼠模擬;你必須擁有一個真實啟用觸摸的裝置才能發射它。

參數

touchPositions: Array

一個 Luau 陣列的 Vector2 個對象,每個指示所有參與手勢的手指位置。

totalTranslation: Vector2

指示盤子動作已經從起始點走了多遠。

velocity: Vector2

指示每個維度中手勢的執行速度。

指示手勢的 Enum.UserInputState


範例程式碼

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

當玩家使用兩個手指對介面元素施加撓動或拉動動作時,此事件會發生,使用觸摸啟用的裝置。當兩個或更多手指靠近時,會發生 扭曲 ;當它們分開時,會發生 拉拔 。此事件與 GuiObject.TouchPan 同時發生。這個事件有助於允許玩家操縱屏幕上的 UI 元素的尺寸(尺寸),最常用於縮放功能。

這個事件發射時使用 Vector2 桌子來描述參與手勢的手指相對畫面位置。此外,它會多次發射:Enum.UserInputState.Begin在短暫延遲後,Enum.UserInputState.Change當玩家在姿勢期間移動手指時,最後使用 Enum.UserInputState.End 。應該注意的是,比例應該用作乘數 由於此事件需要至少兩個手指,因此無法使用模擬器和滑鼠在 Studio 中模擬;您必須擁有一個真實啟用觸摸的裝置。

參數

touchPositions: Array

一個由 Vector2 個物件組成的 Luau 陣列,每個指示所有涉及按壓手勢的手指位置。

scale: number

指示從捏造手勢開始的差異的漂浮點。

velocity: number

指示夾取動作速度的漂浮。

指示手勢的 Enum.UserInputState


範例程式碼

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

當玩家使用兩個手指對介面元素施加撓動或拉動動作時,此事件會發生,使用觸摸啟用的裝置。旋轉發生在兩個手指之間線的角度變更時。此事件與 GuiObject.TouchPan 同時發生。這個事件有助於允許玩家在畫面上操縱 UI 元素的旋轉。

這個事件發射時使用 Vector2 桌子來描述參與手勢的手指相對畫面位置。此外,它會多次發射:Enum.UserInputState.Begin在短暫延遲後,Enum.UserInputState.Change當玩家在姿勢期間移動手指時,最後使用 Enum.UserInputState.End

由於此事件需要至少兩個手指,因此無法使用模擬器和滑鼠在 Studio 中模擬;您必須擁有一個真實啟用觸摸的裝置。

參數

touchPositions: Array

一個 Luau 陣列的 Vector2 個對象,每個指示所有參與手勢的手指位置。

rotation: number

一個浮點,表示旋轉從手勢開始時已經進行了多少。

velocity: number

一個浮點,指示手勢的執行速度。

指示手勢的 Enum.UserInputState


範例程式碼

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

當玩家使用具有觸控功能的裝置在 UI 元素上執行滑動動作時,此事件會發生。它以手勢方向(向上、向下、向左或向右)和涉及手勢的觸點數量發射。滑動手勢通常用於在移動用戶介面中變更標籤。

因為這個事件只需要一個手指,所以可以在 Studio 使用模擬器和滑鼠來模擬。

參數

swipeDirection: Enum.SwipeDirection

A Enum.SwipeDirection 指示撥動手勢的方向(向上、向下、向左或向右)。

numberOfTouches: number

手勢中涉及的觸點數量(通常為 1)。


範例程式碼

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

當使用已啟用觸碰的裝置時,玩家在介面元素上執行點擊動作時,此事件會發生。點擊是一種快速的單次觸碰,不需要任何運動參與(長按會發射 GuiObject.TouchLongPress ,移動期間會發射 GuiObject.TouchPan 和/或 GuiObject.TouchSwipe)。它使用描述手指相對位置的 Vector2 對象表發射。

因為這個事件只需要一個手指,所以可以在 Studio 使用模擬器和滑鼠來模擬。

參數

touchPositions: Array

一個由 組成的陣列,用於描述參與手勢的手指的相對位置。


範例程式碼

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)