GuiObject

Tampilkan yang Tidak Digunakan Lagi

*Konten ini diterjemahkan menggunakan AI (Beta) dan mungkin mengandung kesalahan. Untuk melihat halaman ini dalam bahasa Inggris, klik di sini.

Tidak Dapat Dibuat
Tidak Dapat Dijelajahi

GuiObject adalah kelas abstrak (mirip dengan BasePart ) untuk objek antarmuka pengguna 2D.Ini mendefinisikan semua properti yang terkait dengan tampilan antarmuka pengguna grafis (GUI) seperti Size dan Position .Ini juga memiliki beberapa properti baca hanya yang berguna seperti AbsolutePosition , AbsoluteSize , dan AbsoluteRotation .

Untuk memanipulasi tata letak objek GUI dengan cara khusus, Anda dapat menggunakan struktur tata letak seperti daftar/flex atau grid , dan Anda dapat menyesuaikan tampilan mereka di luar properti inti mereka melalui modifikasi penampilan .

Meskipun mungkin untuk mendeteksi peristiwa tombol mouse pada objek GUI apa pun menggunakan InputBegan dan InputEnded, hanya ImageButton dan TextButton yang memiliki acara khusus yang nyaman seperti Activated untuk mendeteksi klik/tekan.

Rangkuman

Properti

Properti diwarisi dari GuiBase2d

Metode

Acara

Acara diwarisi dari GuiBase2d

Properti

Active

Baca Paralel

Properti ini menentukan apakah GuiObject akan menyinkronkan input ke ruang 3D, seperti model dasar dengan kelas ClickDetector seperti DragDetector.

Untuk GuiButton objek ( ImageButton dan TextButton ), properti ini menentukan apakah Activated api terbakar ( AutoButtonColor masih akan berfungsi untuk mereka juga).Peristiwa InputBegan , InputChanged , dan InputEnded bekerja seperti biasa tidak peduli nilai properti ini.

Contoh Kode

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

Baca Paralel

Properti ini menentukan titik asal dari GuiObject , relatif terhadap ukuran absolutnya.Titik asal menentukan dari mana elemen diposisikan (melalui GuiObject.Position ) dan dari mana ia diperluas (melalui GuiObject.Size ).

Lihat di sini untuk ilustrasi diagram dan rincian.

Contoh Kode

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

Baca Paralel

Properti ini digunakan untuk secara otomatis menyesuaikan objek UI orang tua berdasarkan ukuran keturunannnya.Anda dapat menggunakan properti ini untuk menambahkan teks dan konten lain secara dinamis ke objek UI saat diedit atau dijalankan, dan ukurannya akan disesuaikan untuk sesuai dengan konten itu.

Ketika AutomaticSize diatur ke nilai Enum.AutomaticSize untuk apa pun selain None, objek UI ini dapat diubah ukurannya tergantung pada konten anaknya.

Untuk informasi lebih lanjut tentang cara menggunakan properti ini dan bagaimana cara kerjanya, silakan lihat di sini .

Contoh Kode

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

Baca Paralel

Properti ini menentukan warna latar belakang GuiObject (warna isian).Jika elemen Anda berisi teks, seperti TextBox , TextButton , atau TextLabel , pastikan warna latar belakang kontras dengan warna teks.

Properti lain yang menentukan properti visual latar belakang adalah GuiObject.BackgroundTransparency ; jika ini diatur ke 1, baik latar belakang maupun perbatasan tidak akan ditampilkan.

Lihat juga BorderColor3 .

Contoh Kode

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

Baca Paralel

Properti ini menentukan transparansi latar belakang dan border GuiObject .Namun, ia tidak menentukan transparansi teks jika GUI adalah TextBox , TextButton , atau TextLabel ; transparansi teks ditentukan TextBox.TextTransparency , TextButton.TextTransparency , dan TextLabel.TextTransparency masing-masing.

Jika properti ini diatur ke 1, baik latar belakang maupun perbatasan tidak akan ditampilkan dan latar belakang GUI akan benar-benar transparan.

BorderColor3

Baca Paralel

Menentukan warna border persegi panjang GuiObject (juga dikenal sebagai warna garis).Ini terpisah dari GuiObject.BackgroundColor3 objek.Anda tidak akan dapat melihat batas objek jika properti GuiObject.BorderSizePixel diatur ke 0.

Perhatikan bahwa komponen UIStroke memungkinkan efek perbatasan yang lebih maju.

Contoh Kode

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

Baca Paralel

Properti ini menentukan dengan cara apa perbatasan GuiObject diuraikan relatif terhadap dimensinya menggunakan enum dengan nama yang sama, Enum.BorderMode .

Perhatikan bahwa UIStroke dapat menggantikan properti ini dan memungkinkan efek perbatasan yang lebih maju.

BorderSizePixel

Baca Paralel

Properti ini menentukan seberapa lebar perbatasan GuiObject di render, dalam piksel. Mengatur ini menjadi 0 mematikan perbatasan sama sekali.

Perhatikan bahwa UIStroke dapat menggantikan properti ini dan memungkinkan efek perbatasan yang lebih maju.

Contoh Kode

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

Baca Paralel

Properti ini menentukan apakah GuiObject akan memotong (membuat tidak terlihat) bagian mana pun dari elemen GUI turunan yang sebaliknya akan ditampilkan di luar batas kotak.

Perhatikan bahwa Rotation tidak didukung oleh properti ini.Jika ini atau leluhur GUI apa pun memiliki non-nol , properti ini diabaikan dan elemen GUI keturunan akan ditampilkan terlepas dari nilai properti ini.

Hanya Baca
Tidak Direplikasi
Baca Paralel

Ketika jari pemain ditekan dan dipegang di GuiObject , GuiState dari GuiObject akan diatur ke Press .Demikian pula, ketika jari pemain dilepaskan dari GuiObject , jari GuiState dari GuiObject akan diatur ke Idle , dan ketika Interactable dimatikan di GuiObject , jari Class.GuiState dari GuiObject akan diatur ke NonInteractable .

Interactable

Baca Paralel

Menentukan apakah GuiButton dapat berinteraksi atau tidak, atau apakah GuiState dari GuiObject berubah atau tidak.

Pada GuiButton :

Pada GuiObject :

LayoutOrder

Baca Paralel

Properti ini mengontrol urutan penyortiran dari GuiObject ketika menggunakan UIGridStyleLayout (seperti UIListLayout atau UIPageLayout ) dengan SortOrder diatur ke Enum.SortOrder.LayoutOrder .Ini tidak memiliki fungsi jika objek tidak memiliki struktur UI layout saudara.

GuiObjects diurutkan dalam urutan menaik dengan nilai yang lebih rendah mendapat prioritas atas nilai yang lebih tinggi.Objek dengan nilai yang sama jatuh kembali ke urutan di mana mereka ditambahkan.

Jika Anda tidak yakin apakah Anda perlu menambahkan elemen di antara dua elemen yang ada di masa depan, adalah praktik yang baik untuk menggunakan multiplikasi dari 100 ( 0 , 100 , 200 , dll.).Ini memastikan celah besar nilai urutan tata letak yang dapat Anda gunakan untuk elemen yang diperintahkan di antara elemen lain.

Lihat juga ZIndex yang menentukan urutan penyajian objek rendering alih-alih mengurutkan urutan.

NextSelectionDown

Baca Paralel

Properti ini mengatur GuiObject yang dipilih saat pengguna memindahkan gamepad selektor ke bawah.Jika properti ini kosong, memindahkan gamepad ke bawah tidak akan mengubah GUI yang dipilih.

Memindahkan pemilih gamepad ke bawah menetapkan GuiService.SelectedObject ke objek ini kecuali GUI tidak Selectable .Perhatikan bahwa properti ini dapat ditetapkan ke elemen GUI bahkan jika itu bukan Selectable, jadi Anda harus memastikan bahwa nilai properti GUI yang dapat dipilih sesuai dengan perilaku yang diharapkan.

Lihat juga NextSelectionUp , NextSelectionLeft , dan NextSelectionRight .

Contoh Kode

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

Baca Paralel

Properti ini menetapkan GuiObject yang dipilih saat pengguna memindahkan selektor gamepad ke kiri.Jika properti ini kosong, memindahkan gamepad ke kiri tidak akan mengubah GUI yang dipilih.

Memindahkan pemilih gamepad ke kiri menetapkan GuiService.SelectedObject ke objek ini kecuali GUI tidak Selectable .Perhatikan bahwa properti ini dapat ditetapkan ke elemen GUI bahkan jika itu bukan Selectable, jadi Anda harus memastikan bahwa nilai properti GUI yang dapat dipilih sesuai dengan perilaku yang diharapkan.

Lihat juga NextSelectionUp , NextSelectionDown , dan NextSelectionRight .

Contoh Kode

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

Baca Paralel

Properti ini menetapkan GuiObject yang dipilih saat pengguna memindahkan selektor gamepad ke kanan.Jika properti ini kosong, memindahkan gamepad ke kanan tidak akan mengubah GUI yang dipilih.

Memindahkan pemilih gamepad ke kanan menetapkan GuiService.SelectedObject ke objek ini kecuali GUI tidak Selectable .Perhatikan bahwa properti ini dapat ditetapkan ke elemen GUI bahkan jika itu bukan Selectable, jadi Anda harus memastikan bahwa nilai properti GUI yang dapat dipilih sesuai dengan perilaku yang diharapkan.

Lihat juga NextSelectionUp , NextSelectionDown , dan NextSelectionLeft .

Contoh Kode

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

Baca Paralel

Properti ini menetapkan GuiObject yang dipilih saat pengguna memindahkan selektor gamepad ke atas.Jika properti ini kosong, memindahkan gamepad ke atas tidak akan mengubah GUI yang dipilih.

Memindahkan pemilih gamepad ke atas menetapkan GuiService.SelectedObject ke objek ini kecuali GUI tidak Selectable .Perhatikan bahwa properti ini dapat ditetapkan ke elemen GUI bahkan jika itu bukan Selectable, jadi Anda harus memastikan bahwa nilai properti GUI yang dapat dipilih sesuai dengan perilaku yang diharapkan.

Lihat juga NextSelectionDown , NextSelectionLeft , NextSelectionRight .

Contoh Kode

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

Baca Paralel

Properti ini menentukan piksel dan posisi skalar menggunakan . Posisi ditempatkan di sekitar objek .

Posisi skalar relatif terhadap ukuran elemen GUI orangtua, jika ada.

Bagian piksel dari nilai UDim2 memiliki ukuran yang sama terlepas dari ukuran GUI orangtua.Nilai-nilai mewakili posisi objek dalam piksel.Posisi piksel aktual dari sebuah objek dapat dibaca dari properti GuiBase2d.AbsolutePosition.

Rotation

Baca Paralel

Properti ini menentukan jumlah derajat di mana GuiObject diputar.Rotasi relatif terhadap pusat dari objek, tidak dari , artinya Anda tidak dapat mengubah titik rotasi.Selain itu, properti ini tidak kompatibel dengan ClipsDescendants .

Selectable

Baca Paralel

Properti ini menentukan apakah GuiObject dapat dipilih saat menavigasi GUI menggunakan gamepad.

Jika properti ini adalah true , GUI dapat dipilih. Memilih GUI juga mengatur properti GuiService.SelectedObject ke objek itu.

Ketika ini adalah false, GUI tidak dapat dipilih.Namun, mengatur ini ke false ketika GUI dipilih tidak akan menghapusnya atau mengubah nilai properti GuiService.SelectedObject.

Tambahkan GuiObject.SelectionGained dan GuiObject.SelectionLost tidak akan menembak untuk elemen. Untuk menghapus GuiObject, Anda harus mengubah properti GuiService.SelectedObject.

Properti ini berguna jika GUI terhubung ke beberapa GUI melalui properti seperti ini GuiObject.NextSelectionUp , GuiObject.NextSelectionDown , NextSelectionRight , atau NextSelectionLeft .Daripada mengubah semua properti sehingga Gamepad tidak dapat memilih GUI, Anda dapat menonaktifkan properti yang dapat dipilih untuk sementara mencegahnya dipilih.Kemudian, ketika Anda ingin pemilih gamepad dapat memilih GUI, cukup aktifkan kembali properti yang dapat dipilihnya.

Contoh Kode

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

Baca Paralel

Properti ini menggantikan dekorasi seleksi default yang digunakan untuk gamepad.

Perhatikan bahwa yang dipilih SelectionImageObject melapisi GuiObject yang dipilih dengan Size dari gambar.Untuk hasil terbaik, Anda harus menyesuaikan kustom SelectionImageObject melalui nilai skala UDim2 untuk membantu memastikan bahwa objek skala dengan benar di atas elemen yang dipilih.

Mengubah SelectionImageObject untuk elemen GuiObject hanya memengaruhi elemen itu. Untuk memengaruhi semua elemen GUI pengguna, atur properti PlayerGui.SelectionImageObject.

Untuk menentukan atau mengatur elemen GUI mana yang dipilih oleh pengguna, Anda dapat menggunakan properti GuiService.SelectedObject.Pemain menggunakan gamepad untuk memilih elemen GUI yang berbeda, memanggil NextSelectionUp , NextSelectionDown , NextSelectionLeft , dan NextSelectionRight peristiwa.

SelectionOrder

Baca Paralel

GuiObjects dengan Pesanan Seleksi yang lebih rendah dipilih lebih awal daripada GuiObjects dengan Pesanan Seleksi yang lebih tinggi saat memulai pemilihan gamepad atau memanggil GuiService:Select() pada leluhur.Properti ini tidak memengaruhi navigasi arah.Nilai default adalah 0.

Size

Baca Paralel

Properti ini menentukan skala GuiObject dan ukuran piksel menggunakan UDim2.

Ukuran skalar relatif terhadap ukuran elemen GUI orangtua, jika ada.

Bagian piksel dari nilai UDim2 memiliki ukuran yang sama terlepas dari ukuran GUI orangtua.Nilai-nilai mewakili ukuran objek dalam piksel.Ukuran piksel aktual dari sebuah objek dapat dibaca dari properti GuiBase2d.AbsoluteSize.

Jika GuiObject memiliki orangtua, ukurannya di setiap sumbu juga dipengaruhi oleh orangtuanya SizeConstraint.

Contoh Kode

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

Baca Paralel

Properti ini mengatur sumbu yang akan didasarkan pada, relatif terhadap ukuran orang tuanya.

Properti ini berguna untuk membuat objek GUI yang dimaksudkan untuk diskalakan dengan lebar atau ketinggian objek orang tua, tetapi tidak keduanya, secara efektif mempertahankan rasio aspek objek.

Transparency

Tersembunyi
Tidak Direplikasi
Baca Paralel

Properti campuran dari BackgroundTransparency dan TextTransparency.

Visible

Baca Paralel

Properti ini apakah GuiObject dan keturunannnya akan ditampilkan.

Rendering komponen individu dari GuiObject dapat dikontrol secara individual melalui properti transparansi seperti GuiObject.BackgroundTransparency , TextLabel.TextTransparency dan ImageLabel.ImageTransparency .

Ketika properti ini adalah false , GuiObject akan diabaikan oleh struktur tata letak seperti UIListLayout , UIGridLayout , dan UITableLayout .Dengan kata lain, ruang yang seharusnya diisi oleh elemen digunakan oleh elemen lain sebagai gantinya.

Contoh Kode

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

Baca Paralel

Properti ini menentukan urutan di mana sebuah GuiObject ditampilkan relatif terhadap yang lain.

Secara default, GuiObjects render dalam urutan prioritas menaik di mana mereka dengan nilai ZIndex yang lebih rendah ditampilkan di bawah mereka dengan nilai yang lebih tinggi.Anda dapat mengubah urutan rendering dalam ScreenGui , SurfaceGui , atau BillboardGui dengan mengubah nilai dari ZIndexBehavior nya.

Jika Anda tidak yakin apakah Anda perlu menambahkan elemen di antara dua elemen yang ada di masa depan, adalah praktik yang baik untuk menggunakan multiplikasi dari 100 ( 0 , 100 , 200 , dll.).Ini memastikan celah besar nilai urutan render yang dapat Anda gunakan untuk elemen yang diletakkan di antara elemen lain.

Lihat juga LayoutOrder yang mengontrol urutan penyortiran dari sebuah GuiObject ketika digunakan dengan struktur tata letak seperti UIListLayout atau UIGridLayout .

Metode

TweenPosition

Dengan lancar memindahkan GUI ke posisi baru UDim2 pada waktu yang ditentukan menggunakan Enum.EasingDirection dan Enum.EasingStyle .

Fungsi ini akan kembali apakah remaja akan bermain.Ini tidak akan dimainkan jika remaja lain bertindak di GuiObject dan parameter penghapus adalah false .

Lihat juga GuiObject:TweenSize() dan GuiObject:TweenSizeAndPosition().

Parameter

endPosition: UDim2

Di mana GUI harus bergerak ke.

Nilai Default: ""
easingDirection: Enum.EasingDirection

Arah di mana untuk memudahkan GUI ke posisi akhir.

Nilai Default: "Out"
easingStyle: Enum.EasingStyle

Gaya di mana untuk memudahkan GUI ke posisi akhir.

Nilai Default: "Quad"
time: number

Sudah berapa lama, dalam detik, remaja harus menyelesaikan.

Nilai Default: 1
override: boolean

Apakah remaja akan menggantikan remaja yang sedang berlangsung.

Nilai Default: false
callback: function

Fungsi panggil balas untuk dieksekusi saat remaja selesai.

Nilai Default: "nil"

Memberikan nilai

Apakah remaja akan bermain.

Contoh Kode

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

Mengubah ukuran GuiObject ke ukuran baru UDim2 dalam waktu yang ditentukan menggunakan Enum.EasingDirection dan Enum.EasingStyle yang ditentukan.

Fungsi ini akan kembali apakah remaja akan bermain.Biasanya ini akan selalu kembali true , tetapi akan kembali false jika remaja lain aktif dan invalidasi diatur ke false .

Lihat juga GuiObject:TweenSize() dan GuiObject:TweenSizeAndPosition().

Parameter

endSize: UDim2

Ukuran yang harus diubah oleh GUI.

Nilai Default: ""
easingDirection: Enum.EasingDirection

Arah di mana untuk memudahkan GUI ke ukuran akhir.

Nilai Default: "Out"
easingStyle: Enum.EasingStyle

Gaya di mana untuk memudahkan GUI ke ukuran akhir.

Nilai Default: "Quad"
time: number

Sudah berapa lama, dalam detik, remaja harus menyelesaikan.

Nilai Default: 1
override: boolean

Apakah remaja akan menggantikan remaja yang sedang berlangsung.

Nilai Default: false
callback: function

Fungsi panggil balas untuk dieksekusi saat remaja selesai.

Nilai Default: "nil"

Memberikan nilai

Apakah remaja akan bermain.

Contoh Kode

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

Mengubah ukuran dan posisi GUI dengan lancar ke ukuran dan posisi baru UDim2 pada waktu yang ditentukan menggunakan Enum.EasingDirection dan Enum.EasingStyle .

Fungsi ini akan kembali apakah remaja akan bermain.Biasanya ini akan selalu kembali true , tetapi akan kembali false jika remaja lain aktif dan invalidasi diatur ke false .

Lihat juga GuiObject:TweenSize() dan GuiObject:TweenSizeAndPosition().

Parameter

endSize: UDim2

Ukuran yang harus diubah oleh GUI.

Nilai Default: ""
endPosition: UDim2

Di mana GUI harus bergerak ke.

Nilai Default: ""
easingDirection: Enum.EasingDirection

Arah di mana untuk memudahkan GUI ke ukuran akhir dan posisi akhir.

Nilai Default: "Out"
easingStyle: Enum.EasingStyle

Gaya di mana untuk memudahkan GUI ke ukuran akhir dan posisi akhir.

Nilai Default: "Quad"
time: number

Sudah berapa lama, dalam detik, remaja harus menyelesaikan.

Nilai Default: 1
override: boolean

Apakah remaja akan menggantikan remaja yang sedang berlangsung.

Nilai Default: false
callback: function

Fungsi panggil balas untuk dieksekusi saat remaja selesai.

Nilai Default: "nil"

Memberikan nilai

Apakah remaja akan bermain.

Contoh Kode

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

Acara

InputBegan

Peristiwa ini terjadi ketika pengguna mulai berinteraksi dengan GuiObject melalui perangkat Antarmuka Manusia-Komputer (tombol mouse turun, sentuhan mulai, tombol keyboard turun, dll).

The UserInputService memiliki peristiwa berjudul serupa yang tidak terbatas pada elemen UI tertentu: UserInputService.InputBegan .

Acara ini akan selalu menembak terlepas dari status permainan.

Lihat juga GuiObject.InputEnded dan GuiObject.InputChanged.

Parameter

Sebuah InputObject , yang berisi data berguna untuk meminta masukan pengguna seperti type of input , state of input , dan screen coordinates of the input .


Contoh Kode

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

Peristiwa ini terjadi ketika pengguna mengubah cara mereka berinteraksi melalui perangkat Antarmuka Manusia-Komputer (tombol mouse turun, sentuhan mulai, tombol keyboard turun, dll).

The UserInputService memiliki peristiwa berjudul serupa yang tidak terbatas pada elemen UI tertentu: UserInputService.InputChanged .

Acara ini akan selalu menembak terlepas dari status permainan.

Lihat juga GuiObject.InputBegan dan GuiObject.InputEnded.

Parameter

Sebuah InputObject , yang berisi data berguna untuk meminta masukan pengguna seperti type of input , state of input , dan screen coordinates of the input .


Contoh Kode

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

Acara InputEnded terjadi ketika pengguna berhenti berinteraksi melalui perangkat Antarmuka Manusia-Komputer (tombol mouse turun, sentuhan mulai, tombol keyboard turun, dll).

The UserInputService memiliki peristiwa berjudul serupa yang tidak terbatas pada elemen UI tertentu: UserInputService.InputEnded .

Acara ini akan selalu menembak terlepas dari status permainan.

Lihat juga GuiObject.InputBegan dan GuiObject.InputChanged.

Parameter

Sebuah InputObject , yang berisi data berguna untuk meminta masukan pengguna seperti Enum.UserInputType , Enum.UserInputState , dan InputObject.Position .


Contoh Kode

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

Acara MouseEnter terjadi ketika pengguna memindahkan mouse ke elemen GuiObject .

Silakan jangan bergantung pada argumen x dan y yang disampaikan oleh peristiwa ini sebagai cara mudah untuk menentukan di mana mouse pengguna berada saat masuk ke GUI.Koordinat ini dapat bervariasi bahkan ketika mouse memasuki GUI melalui sisi yang sama - terutama ketika mouse memasuki elemen dengan cepat.Ini karena koordinat menunjukkan posisi mouse saat peristiwa terjadi daripada saat tepat ketika mouse memasuki GUI.

Acara ini terjadi bahkan ketika elemen GUI disajikan di bawah elemen lain.

Jika Anda ingin melacak kapan mouse pengguna meninggalkan elemen GUI, Anda dapat menggunakan acara GuiObject.MouseLeave.

Lihat Juga

Parameter

Koordinat layar mouse X dalam piksel, relatif dengan sudut kiri atas layar.

Koordinat layar mouse Y relatif terhadap sudut kiri atas layar.


Contoh Kode

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

Acara MouseLeave terjadi ketika pengguna memindahkan mouse mereka keluar dari elemen GuiObject .

Silakan jangan bergantung pada argumen x dan y yang disampaikan oleh peristiwa ini sebagai cara mudah untuk menentukan di mana mouse pengguna berada saat meninggalkan GUI.Koordinat ini dapat bervariasi bahkan ketika mouse meninggalkan GUI melalui sisi yang sama - terutama ketika mouse meninggalkan elemen dengan cepat.Ini karena koordinat menunjukkan posisi mouse saat peristiwa terjadi daripada saat tepat ketika mouse meninggalkan GUI.

Acara ini terjadi bahkan ketika elemen GUI disajikan di bawah elemen lain.

Lihat Juga

Parameter

Koordinat layar mouse X dalam piksel, relatif dengan sudut kiri atas layar.

Koordinat layar mouse Y relatif terhadap sudut kiri atas layar.


MouseMoved

Memicu kebakaran setiap kali pengguna memindahkan mouse saat berada di dalam elemen GuiObject.Ini mirip dengan Mouse.Move , yang menembak terlepas dari apakah mouse pengguna berada di atas elemen GUI.

Catatan, acara ini terbakar saat posisi mouse diperbarui, oleh karena itu akan terbakar berulang kali saat dipindahkan.

Argumen x dan y menunjukkan koordinat layar yang diperbarui dari mouse pengguna dalam piksel.Ini bisa berguna untuk menentukan lokasi mouse di GUI, layar, dan delta karena posisi sebelumnya mouse jika dilacak dalam variabel global.

Kode di bawah ini menunjukkan cara menentukan offset Vector2 dari mouse pengguna terhadap elemen GUI:


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

Perhatikan bahwa acara ini mungkin tidak terbakar persis ketika mouse pengguna memasuki atau keluar dari elemen GUI.Oleh karena itu, argumen x dan y mungkin tidak cocok sempurna dengan koordinat ujung GUI.

Lihat Juga

Parameter

Koordinat layar mouse X dalam piksel, relatif dengan sudut kiri atas layar.

Koordinat layar mouse Y relatif terhadap sudut kiri atas layar.


MouseWheelBackward

Acara WheelBackward terjadi ketika pengguna menggulir roda mouse kembali saat mouse berada di atas elemen GuiObject.Ini mirip dengan Mouse.WheelBackward , yang menembak terlepas dari apakah mouse pengguna berada di atas elemen GUI.

Acara ini hanya menembak sebagai indikator gerakan mundur roda.Ini berarti bahwa argumen koordinat mouse x dan y tidak berubah sebagai hasil dari peristiwa ini.Koordinat ini hanya berubah ketika mouse bergerak, yang dapat dilacak oleh acara GuiObject.MouseMoved .

Lihat Juga

Parameter

Koordinat layar mouse X dalam piksel, relatif dengan sudut kiri atas layar.

Koordinat layar mouse Y relatif terhadap sudut kiri atas layar.


MouseWheelForward

Acara WheelForward terjadi ketika pengguna menggulir roda mouse ke depan saat mouse berada di atas elemen GuiObject.Ini mirip dengan Mouse.WheelForward , yang menembak terlepas dari apakah mouse pengguna berada di atas elemen GUI.

Peristiwa ini hanya menyala sebagai indikator gerakan roda ke depan.Ini berarti bahwa argumen koordinat mouse X dan Y tidak berubah sebagai hasil dari peristiwa ini.Koordinat ini hanya berubah ketika mouse bergerak, yang dapat dilacak oleh acara GuiObject.MouseMoved .

Lihat Juga

Parameter

Koordinat layar mouse X dalam piksel, relatif dengan sudut kiri atas layar.

Koordinat Y dari mouse pengguna.


SelectionGained

Acara ini terjadi ketika pemilih Gamepad mulai fokus pada GuiObject.

Jika Anda ingin memeriksa dari Gamepad pilih berhenti fokus pada elemen GUI, Anda dapat menggunakan acara GuiObject.SelectionLost.

Ketika GUI mendapat fokus pemilihan, nilai properti SelectedObject juga berubah menjadi yang mendapat pemilihan.Untuk menentukan GUI mana yang mendapatkan pilihan, periksa nilai properti ini.


Contoh Kode

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

Acara ini terjadi ketika pemilih Gamepad berhenti fokus pada GuiObject.

Jika Anda ingin memeriksa dari Gamepad pilih mulai fokus pada elemen GUI, Anda dapat menggunakan acara GuiObject.SelectionGained.

Ketika GUI kehilangan fokus seleksi, nilai properti SelectionObject berubah menjadi nil atau ke elemen GUI yang mendapatkan fokus seleksi.Untuk menentukan GUI mana yang mendapatkan pilihan, atau jika tidak ada GUI yang dipilih, periksa nilai properti ini.


Contoh Kode

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

Acara ini terjadi setelah sesaat ketika pemain menahan jari mereka di elemen UI menggunakan perangkat yang mendukung sentuhan.Ini menembak dengan tabel Vector2 yang menggambarkan posisi layar relatif dari jari yang terlibat dalam gerakan.Selain itu, ia menembak beberapa kali: Enum.UserInputState.Begin setelah jeda singkat, Enum.UserInputState.Change jika pemain menggerakkan jari mereka selama gerakan, dan akhirnya Enum.UserInputState.End .Keterlambatan tergantung pada platform; di Studio itu sedikit lebih lama dari satu detik.

Karena acara ini hanya membutuhkan satu jari, acara ini dapat disimulasikan di Studio menggunakan emulator dan mouse.

Parameter

touchPositions: Array

Sebuah array dari Vector2 yang menggambarkan posisi relatif dari jari yang terlibat dalam gerakan.

A Enum.UserInputState yang menggambarkan status gerakan:

  • Mulai api sekali di awal gerakan (setelah jeda singkat)
  • Ubah api jika pemain menggerakkan jari saat menekan
  • Akhiri api sekali di akhir gerakan saat mereka melepaskan jari mereka.

Contoh Kode

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

Acara ini terjadi ketika pemain menggerakkan jari mereka di elemen UI menggunakan perangkat yang mendukung sentuhan.Ini menembak sebelum GuiObject.TouchSwipe akan terbakar, dan tidak menembak dengan GuiObject.TouchTap .Acara ini berguna untuk memungkinkan pemain memanipulasi posisi elemen UI di layar.

Peristiwa ini menembak dengan tabel Vector2 yang menggambarkan posisi layar relatif dari jari yang terlibat dalam gerakan.Selain itu, ia menembak beberapa kali: Enum.UserInputState.Begin setelah jeda singkat, Enum.UserInputState.Change ketika pemain menggerakkan jari mereka selama gerakan, dan akhirnya dengan Enum.UserInputState.End .

Acara ini tidak dapat disimulasikan di Studio menggunakan emulator dan mouse; Anda harus memiliki perangkat yang benar-benar dapat diaktifkan sentuhan untuk menembaknya.

Parameter

touchPositions: Array

Sebuah array Luau dari Vector2 objek, masing-masing menunjukkan posisi semua jari yang terlibat dalam gerakan.

totalTranslation: Vector2

Menunjukkan seberapa jauh gerakan wajan telah berjalan dari titik awalnya.

velocity: Vector2

Menunjukkan seberapa cepat gerakan dilakukan di setiap dimensi.

Menunjukkan Enum.UserInputState dari gerakan.


Contoh Kode

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

Acara ini terjadi ketika pemain menggunakan dua jari untuk membuat gerakan geser atau tarik pada elemen UI menggunakan perangkat yang mendukung sentuhan.Sebuah siput terjadi ketika dua atau lebih jari bergerak lebih dekat bersama, dan sebuah tarik terjadi ketika mereka bergerak terpisah.Acara ini terjadi bersamaan dengan GuiObject.TouchPan .Acara ini berguna untuk memungkinkan pemain memanipulasi skala (ukuran) elemen UI di layar, dan paling sering digunakan untuk fitur zooming.

Peristiwa ini menembak dengan tabel Vector2 yang menggambarkan posisi layar relatif dari jari yang terlibat dalam gerakan.Selain itu, ia menembak beberapa kali: Enum.UserInputState.Begin setelah jeda singkat, Enum.UserInputState.Change ketika pemain menggerakkan jari selama gerakan, dan akhirnya dengan Enum.UserInputState.End .Harus dicatat bahwa skala harus digunakan secara multiplikatif .

Karena acara ini memerlukan setidaknya dua jari, tidak mungkin untuk menyimpulkannya di Studio menggunakan emulator dan mouse; Anda harus memiliki perangkat yang benar-benar dapat disentuh.

Parameter

touchPositions: Array

Sebuah array Luau dari Vector2 objek, masing-masing menunjukkan posisi semua jari yang terlibat dalam gerakan pinch.

scale: number

Pengapung yang menunjukkan perbedaan dari awal gerakan pinch.

velocity: number

Sebuah float yang menunjukkan seberapa cepat gerakan pinch terjadi.

Menunjukkan Enum.UserInputState dari gerakan.


Contoh Kode

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

Acara ini terjadi ketika pemain menggunakan dua jari untuk membuat gerakan geser atau tarik pada elemen UI menggunakan perangkat yang mendukung sentuhan.Rotasi terjadi ketika sudut garis antara dua jari berubah.Peristiwa ini terjadi bersamaan dengan GuiObject.TouchPan .Acara ini berguna untuk memungkinkan pemain memanipulasi rotasi elemen UI di layar.

Peristiwa ini menembak dengan tabel Vector2 yang menggambarkan posisi layar relatif dari jari yang terlibat dalam gerakan.Selain itu, ia menembak beberapa kali: Enum.UserInputState.Begin setelah jeda singkat, Enum.UserInputState.Change ketika pemain menggerakkan jari selama gerakan, dan akhirnya dengan Enum.UserInputState.End .

Karena acara ini memerlukan setidaknya dua jari, tidak mungkin untuk disimulasikan di Studio menggunakan emulator dan mouse; Anda harus memiliki perangkat yang benar-benar dapat disentuh.

Parameter

touchPositions: Array

Sebuah array Luau dari Vector2 objek, masing-masing menunjukkan posisi semua jari yang terlibat dalam gerakan.

rotation: number

Sebuah float yang menunjukkan berapa banyak rotasi telah berlalu dari awal gerakan.

velocity: number

Sebuah float yang menunjukkan seberapa cepat gerakan dilakukan.

Menunjukkan Enum.UserInputState dari gerakan.


Contoh Kode

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

Acara ini terjadi ketika pemain melakukan gerakan geser pada elemen UI menggunakan perangkat yang mendukung sentuhan.Ini menembak dengan arah gerakan (Naik, Turun, Kiri atau Kanan) dan jumlah titik sentuhan yang terlibat dalam gerakan.Gerakan geser sering digunakan untuk mengubah tab di UI seluler.

Karena acara ini hanya membutuhkan satu jari, itu dapat disimulasikan di Studio menggunakan emulator dan mouse.

Parameter

swipeDirection: Enum.SwipeDirection

A Enum.SwipeDirection menunjukkan arah gerakan gesek (Atas, Bawah, Kiri atau Kanan).

numberOfTouches: number

Jumlah titik sentuhan yang terlibat dalam gerakan (biasanya 1).


Contoh Kode

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

Peristiwa ini terjadi ketika pemain melakukan gerakan geser di elemen UI menggunakan perangkat yang mendukung sentuhan.Sentuhan adalah sentuhan cepat tanpa ada gerakan yang terlibat (tekan lebih lama akan menembakkan GuiObject.TouchLongPress , dan bergerak selama sentuhan akan menembakkan GuiObject.TouchPan dan/atau GuiObject.TouchSwipe ).Ini menembak dengan tabel Vector2 objek yang menggambarkan posisi relatif jari yang terlibat dalam gerakan.

Karena acara ini hanya membutuhkan satu jari, itu dapat disimulasikan di Studio menggunakan emulator dan mouse.

Parameter

touchPositions: Array

Sebuah array dari Vector2 yang menggambarkan posisi relatif dari jari yang terlibat dalam gerakan.


Contoh Kode

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)