Skip to content

User interface

Every piece of interface is an Entity with 2D layout components: a root entity at the top, with panels, labels, buttons and images under it. A client script builds and updates the interface and handles its clicks. When a click needs to change the game, the client script sends a Net message to the server.

Put UI on the screen

Spawn a root entity with UIRoot set to true, parent it to World.Viewport.Screen, and put elements under it. An element under World.Viewport.Screen draws only when it or an ancestor has UIRoot. As with any entity, give it its components when you spawn it and set Parent last.

-- Client script.
local hud = World.Spawn({ UIRoot = true })
hud.Name = "HUD"
hud.Parent = World.Viewport.Screen

local panel = World.Spawn({
    Box = {
        Size = UIVector.fromPoints(240, 80),
        Position = UIVector.fromPoints(16, 16),
    },
    Panel = {},
})
panel.Parent = hud

local score = World.Spawn({
    Box = { Size = UIVector.fromScale(1, 1) },
    UITextSource = { Text = "Score: 0" },
    UITextStyle = { TextSize = 24 },
})
score.Parent = panel

Each component adds one behavior. Box places and sizes the element and is what makes an entity part of the interface. Panel draws a background, UITextSource and UITextStyle draw text, Image draws a texture, and Button lets the element take the pointer. Read and write an element through these components: score.UITextSource is the label's text view, or nil when the entity does not have that component; see component views. An entity is either in the 3D world or in the interface: World.Spawn refuses a table that mixes 3D and interface components.

In Studio, Home > UI inserts ready-made elements into the selected interface element. With none selected, the new element goes into the place's first screen root, or into a new one when the place has none. Each one starts with a set of components:

Interface built in Studio replicates to each player when they join. Once the join finishes, that player's client takes over every screen root it received and everything under it: client scripts change it for that player only, and the client ignores the server's later changes to those elements. A child the server adds under one of them arrives hidden, and a screen root the server adds after the join stays the server's. To update a player's screen from the server, send a Net.ToClients message and let a client script apply it.

Put UI on a part

An entity with the UISurface component draws its children on one face of its parent part, chosen by SurfaceFace. A surface whose parent is not a part draws nothing.

-- Server script in a part.
local sign = World.Spawn({ UISurface = { SurfaceFace = "Back" } })
sign.Parent = self

local label = World.Spawn({
    Box = { Size = UIVector.fromScale(1, 1) },
    UITextSource = { Text = "Welcome" },
    UITextStyle = { TextSize = 48 },
})
label.Parent = sign

SurfacePixelsPerUnit sets how many canvas pixels cover one unit of the face; at 0, the canvas takes SurfaceCanvasSizeX by SurfaceCanvasSizeY pixels. SurfaceLightInfluence sets how much scene lights shade the canvas, and the UISurfaceAlwaysOnTop component draws it in front of everything in the 3D scene. Buttons on a surface take clicks; SurfaceMaxDistance limits how far away the player can use them.

A BillboardGui is a canvas that floats over its parent and always faces the camera, such as a name over a character, and its children lay out on it as on a surface. Its size and placement are fields of its BillboardGui component, as in tag.BillboardGui.Width = 160: Width and Height in interface points, UnitsOffset from the parent, and MaxDistance, past which it hides after fading over the last 30%. A wall between the camera and the billboard hides it unless AlwaysOnTop is true. Buttons on a billboard do not take the pointer.

For a line of text over a part, the Billboard component is enough, with no canvas or child elements:

-- Server script in a part.
self:Add(Component.Billboard)
local tag = self.Billboard
if tag then
    tag.BillboardText = "Shop"
    tag.BillboardOffset = Vector3.new(0, 3, 0)
    tag.BillboardMaxDistance = 60
end

To show what a camera sees, a portal or a mirror on a face of a part, give the part a SurfaceView instead.

Position and size an element

The Box component's Position and Size are UIVector values. Each has a scale, the share of the parent's size where 1 is 100%, plus a fixed number of points. Make them with UIVector.new, UIVector.fromScale or UIVector.fromPoints; UIVector.new takes (scaleX, scaleY, pointsX, pointsY), both scales first.

AnchorPoint picks the point of the element that Position places: Vector2.new(0, 0) is its top left, (0.5, 0.5) its center and (1, 1) its bottom right. Along each axis:

size = parentSize * size.Scale + size.Points
left = parentLeft + parentSize * position.Scale + position.Points
       - size * anchor

This dialog stays centered on any screen. On an 800 by 600 screen its left edge is at 800 × 0.5 - 400 × 0.5 = 200 and its top at 600 × 0.5 - 300 × 0.5 = 150; on a 1920 by 1080 screen they move to 760 and 390.

-- Client script, after the HUD above.
local dialog = World.Spawn({
    Box = {
        Size = UIVector.fromPoints(400, 300),
        Position = UIVector.fromScale(0.5, 0.5),
        AnchorPoint = Vector2.new(0.5, 0.5),
    },
    Panel = {},
})
dialog.Parent = hud

To move it later, write Position on its Box view. These Box fields adjust the size that Size gives:

  • SizeModeX and SizeModeY choose how each axis is sized: "Fixed" uses Size, "Fit" sizes the axis to the element's text or children, and "Grow" fills the room the parent gives, shared among the "Grow" children of a list.
  • MinSize and MaxSize set the smallest and largest size layout gives the element. MinSize wins when they conflict.
  • AspectRatio fixes width divided by height. The element takes the largest box of that shape that fits in its Size.

The Box view's ScreenPosition and ScreenSize read where layout put the element on screen and how big it ended up, in points.

The UIScreenInsets component with ScreenInsets set to "CoreUISafeInsets" keeps a screen element clear of the screen edges the platform interface uses, such as the top bar; "TopbarSafeInsets" keeps it clear of the top edge only. A 3D property on an interface element, or an interface property on a part, fails with one of the interface layout errors.

Style a box

The Panel component draws a background: BackgroundColor and BackgroundTransparency set the fill. The Border component draws a border inside the edges, with BorderSizePixel and BorderColor, and the UICorner component rounds the corners by its radius in pixels. Every transparency runs from 0 (opaque) to 1 (invisible).

-- Client script, after the HUD above.
local card = World.Spawn({
    Box = { Size = UIVector.fromPoints(320, 120) },
    Panel = {
        BackgroundColor = Color.fromRGB(32, 36, 44),
        BackgroundTransparency = 0.1,
    },
    Border = {
        BorderColor = Color.fromRGB(80, 90, 110),
        BorderSizePixel = 1,
    },
    UICorner = 8,
    GroupOpacity = 1,
})
card.Parent = hud

Visible set to false hides an element and everything under it, and the hidden elements stop taking the pointer. The GroupOpacity component fades an element and everything under it as one group, from 1 (as built) to 0 (invisible), the opposite of GroupTransparency; Tween.Play(card, Component.GroupOpacity, 0, 0.3) fades the card above out. The UIClips component cuts off children at the element's edges.

Show text

UITextSource holds the Text, and UITextStyle draws it: TextSize is its height in pixels, from 1 to 512, TextColor its color, FontFamily picks one of the built-in typefaces and FontWeight its weight. TextStrokeWidth with TextStrokeTransparency below 1 draws an outline.

-- Client script, after the HUD above.
local title = World.Spawn({
    Box = { SizeModeX = "Fit", SizeModeY = "Fit" },
    UITextSource = { Text = "Round 1" },
    UITextStyle = {
        TextSize = 32,
        FontFamily = "Montserrat",
        FontWeight = 700,
        TextStrokeWidth = 2,
        TextStrokeTransparency = 0,
    },
})
title.Parent = hud

With "Fit" size modes the label sizes itself to its text. For a paragraph, fix the width, add the UITextWrapped component, which wraps the text at the element's width, and give SizeModeY the value "Fit", so the label grows downward as lines wrap. The UITextTruncate component ends an overlong line with an ellipsis instead. TextXAlignment and TextYAlignment align the text in its box, and the UIRichText component allows <b>, <i> and <font> markup. Set NoTranslate on player names and numbers so they always show as written.

Show an image

The Image component's Image takes the asset ID as a decimal string, because a Luau number cannot hold every 64-bit ID exactly; "0" draws nothing. ImageColor tints the image. The UIImageScale component chooses how the image fills the box with ScaleType ("Stretch", "Slice", "Tile", "Fit" or "Crop"), and its ImageRectOffset with ImageRectSize picks one sprite from a sprite sheet. An image with the Button component is a clickable image, and the UIImageStates component swaps the picture for its HoverImage while the pointer is over it and its PressedImage while the pointer holds it down.

Arrange children in a list or grid

The UIListLayout component makes an element a list: it stacks its visible children top to bottom when Axis is "Vertical", or left to right when it is "Horizontal". Align, Justify, Spacing and margins such as MarginLeft place the children in it. The UIGridLayout component makes it a grid of equal cells instead, sized by CellSize and CellPadding, filled left to right across Columns and then row by row.

A list or grid ignores its children's Position and AnchorPoint; a grid also gives every child the cell size. The UIOrder component's LayoutOrder sets the order: lower numbers come first, and equal numbers keep the order the children were added in. A child with the UIFloating component stays out of the list and uses its own position.

-- Client script, after the HUD above: nine slots along the bottom.
local bar = World.Spawn({
    Box = {
        AnchorPoint = Vector2.new(0.5, 1),
        Position = UIVector.new(0.5, 1, 0, -16),
        Size = UIVector.fromPoints(0, 56),
        SizeModeX = "Fit",
    },
    UIListLayout = { Axis = "Horizontal", Align = "Center", Spacing = 6 },
})
bar.Parent = hud

local cells = {}
for slot = 1, 9 do
    local cell = World.Spawn({
        Box = { Size = UIVector.fromPoints(48, 48) },
        UIOrder = { LayoutOrder = slot },
        Panel = { BackgroundTransparency = 0.4 },
        UITextSource = { Text = tostring(slot) },
        UITextStyle = {
            TextXAlignment = "Center",
            TextYAlignment = "Center",
        },
        Button = true,
    })
    cell.Name = "Slot" .. slot
    cell.Parent = bar
    cells[slot] = cell
end

A ScrollingFrame has the ScrollFrame component. With a zero CanvasSize it takes its scroll height from a vertical list inside it, so a long list scrolls without a script measuring it, and the UIScrollFollowing component keeps it at the bottom as rows are added. Where elements overlap, the UIOrder component's ZIndex decides which sibling draws on top: higher numbers draw in front, and equal numbers draw in tree order.

Respond to clicks

An element takes the pointer only when it has the Button component; otherwise clicks pass through to whatever is behind it. Connect its signals with the entity's On method, as in cell:On(Component.Button.Clicked, handler). They fire in client scripts:

  • Clicked fires when the player clicks, taps or confirms the element with a gamepad or keyboard.
  • Pressed fires when a press goes down on the element.
  • Released fires when a press comes up over the element.
  • HoverChanged fires when the pointer enters the element, with true, or leaves it, with false.
  • Dragged fires while the pointer drags the element, with the movement as a Vector2.
  • DragEnded fires when the player finishes dragging the element.
  • WheelMoved fires when the mouse wheel turns while the pointer is over the element.

Pointer input never reaches the server. Connecting one of these signals in a server script warns once with Entity.<Signal>: signal cannot fire in a server script; <reason>, connect from a client script (see signal warnings), and the handler never runs. The UIDisabled component dims an element and everything under it and stops them from taking the pointer and keys.

When a click should change the game, send a message. Both scripts declare it with Net.ToServer and the same name and fields; the server handles it with Net.On, and the client sends it with Net.Send:

-- Server script.
local UseSlot = Net.ToServer("UseSlot", { Slot = 0 })

Net.On(UseSlot, function(player: Entity, data)
    print(player.Name, "used slot", data.Slot)
end)
-- Client script, after building the bar above.
local UseSlot = Net.ToServer("UseSlot", { Slot = 0 })

for slot, cell in cells do
    cell:On(Component.Button.HoverChanged, function(entered: boolean)
        local fill = cell.Panel
        if fill then
            fill.BackgroundTransparency = if entered then 0.1 else 0.4
        end
    end)
    cell:On(Component.Button.Clicked, function()
        Net.Send(UseSlot, { Slot = slot })
    end)
end

The server receives the player who sent each message, so a client cannot click on behalf of another player. See Network authority and replication for what replicates and who may write it.

Take typed text and values

A TextBox has the UITextInput component, and what the player types is the UITextSource component's Text. PlaceholderText shows a hint while the box is empty, and MaxLength limits how much the player can type. Focused fires when the player starts typing in the box and FocusLost when they stop, with true when they pressed the return key.

-- Client script, after the HUD above.
local field = World.Spawn({
    Box = { Size = UIVector.fromPoints(240, 32) },
    Panel = {},
    UITextSource = {},
    UITextInput = { PlaceholderText = "Name your pet", MaxLength = 20 },
    Button = true,
})
field.Parent = hud

field:On(Component.UITextInput.FocusLost, function(enterPressed: boolean)
    local source = field.UITextSource
    if enterPressed and source then
        print("named", source.Text)
    end
end)

Sliders, switches and checkboxes keep their value in a component that a client script reads:

  • A stepped slider's UISliderState has Steps and the Value the thumb is on, from 0 to Steps - 1.
  • A free slider's UIFloatSliderValue has the SliderValue between the UIFloatSlider component's MinValue and MaxValue.
  • A switch is on while it has the UIToggleOn component, and a checkbox is checked while it has UIChecked.

Show the world in an element

An element with the UIViewport component draws what a camera sees inside its box, such as a minimap or a character preview. CurrentCamera is the camera entity, and nil draws nothing.

-- Client script, after the HUD above.
local cam = World.Spawn({
    CameraLens = {},
    Position = Vector3.new(0, 20, 30),
})
cam.Parent = World

local view = World.Spawn({
    Box = { Size = UIVector.fromPoints(200, 200) },
    UIViewport = { CurrentCamera = cam },
})
view.Parent = hud

Limits

  • An interface tree is at most 64 levels deep, counting the screen root, surface or billboard.
  • The client lays out at most 8,192 elements at once, across the screen and every surface and billboard. The platform's own interface, such as the menu and chat, counts toward this limit.
  • A place shows at most 256 surface canvases.

Elements past a limit do not appear, and the client log reports ui resolve cut N entities past the depth, node or paint cap: the screen is wrong.

How it works

Only the client lays out and draws the interface. Before it draws a frame, it measures every element from the deepest children up, so a "Fit" parent knows how big its children are, and then places elements from the top down, so each child resolves against its parent's final box. A write to a component shows on the next frame.

Screen elements take the pointer first, then surfaces, found by a ray from the pointer into the world.

Text draws from multi-channel signed distance fields: each glyph is stored once per family, weight and slant, and scaled to any TextSize without blurring, and the outline comes from the same field in the same draw. The first time a script shows a character in a new family, weight or slant, a worker thread renders it and it appears a frame or two later. Its width is known at once, so nothing around the text moves when it appears.