Manual
Manual
UI from code
Each UI document has a C# class, half of it written by the build from the document and half by you. This page covers that class, the events your half hears, reading and setting elements, showing and hiding documents, making documents inside others from code, and binding elements to what the game holds.
A document's class
The build reads every .ui file of your game and writes half of a class for each: a member for each named element, and a partial void for each thing each control can do. You write the other half, in the game's namespace, and implement the handlers you want to hear:
// assets/ui/main menu.ui names its class MainMenu; the build writes Title, Play and the partials.partial class MainMenu{ partial void OnShown() => Title.Text = "Abyss";
partial void OnPlayClicked() => Log.Info("Play");}Pick the document in the Project panel to see its class in the Inspector: its name, what it calls each element, and the handlers it can implement. Create Script writes your half into the scripts folder as MainMenu.cs, the handlers listed in it as comments to fill in; Open Script opens it once it is there. See The document's Inspector.
- An element is a member by its name, made an identifier word by word, as the Inspector's Elements row shows: an element called
Play ButtonisPlayButton. An element with no name is no member. A name the class has already, such asWorldorRoot, or another element's, takes a number after it. - A handler misspelt is a compile error. A
partial voidthe build did not declare has nothing to implement, so a handler left behind by an element renamed in the document stops the build, rather than a click nobody hears. - The class keeps its name as its file is renamed, unless it still has the name the old file gave it. Rename it in the document's Inspector, and it is renamed in its script too.
Events
What each control can do, and the handler that hears it, Play standing for the element's member:
| Element | Handler | Called when |
|---|---|---|
| Button | OnPlayClicked() | It is clicked, pressed and let go of over itself, or pressed by a key or a gamepad |
OnPlayPressed() | The mouse's left button goes down on it, before it is let go of anywhere | |
| Toggle (Checkbox) | OnMusicToggled(bool on) | It is turned on or off |
| Slider | OnVolumeChanged(float value) | It moves, at every step as it is dragged |
OnVolumeChangeEnded(float value) | It is let go of, or stepped by a key | |
| Text field | OnNameChanged() | It is typed into; its Text says what it says now |
OnNameSubmitted(string text) | It is submitted, by Enter or a gamepad's South button | |
| Dropdown | OnQualityChanged(int index) | The player picks another option, at index among its options from 0 |
| The document | OnShown() | It is shown, its elements there |
OnHidden() | It goes: its UI Document names another or goes, it is closed, or the game stops | |
OnCancel() | The UI map's Cancel, Escape or East, while it is modal and the topmost |
A press is what an inventory's slot picks a stack up on, as the mouse goes down, where a click waits for the button to come up over itself. A press on what is inside a button, its icon or its label, is the button's. A disabled button is not pressed, and a key or a gamepad clicks alone.
What your code sets, a toggle turned, a slider moved or a dropdown's option picked from code, is not heard: the code knows already.
partial class Settings{ partial void OnShown() { Music.Checked = true; Volume.Value = 0.5f; }
partial void OnMusicToggled(bool on) => Log.Info(on ? "Music on" : "Music off");
partial void OnVolumeChangeEnded(float value) => Log.Info($"Volume {value:P0}");
partial void OnNameSubmitted(string text) => Log.Info($"Hello, {text}");}The handlers run between frames, on the engine thread, in the order things happened, as a flow does (see Code that is not a system). So they can change the world freely: load, spawn, open another document. Work they start that waits stops with the game. The class reaches the world as World.
Asking from a system
A system can ask instead of being told. world.Ui.Find<T>() gives the class of a document shown, and an element says whether it was clicked or pressed since the frame before:
MainMenu? menu = world.Ui.Find<MainMenu>();if (menu is not null && menu.Play.WasClicked){ // ...}Find gives the first, where several of one document are shown. Find<T>(entity) gives the one an entity's UI Document shows, for a document each of many entities shows, such as a health bar kept over each character by its UI Follow:
world.Ui.Find<HealthBar>(enemy)?.Fill.ToggleClass("low", hitPoints < 20);Read and set elements
Each member is a UiElement. What it can do:
| Member | What it does |
|---|---|
Text | What it says. Set, it says that; an element with no text is given some. |
SetText($"...") | Sets text from an interpolated string without making a string; see below |
Checked | A toggle on or off |
Value | A slider's value, kept in its range |
Picked, PickedText | A dropdown's picked option, by its place from 0, and its words |
Options, SetOptions(words) | A dropdown's options' words; gives it options of your own |
Open(), Close(), IsOpen | Opens a dropdown's list, closes it, and whether it is open |
Focus(), Focused | Gives it focus, so Enter presses it; whether it has focus |
SetImage(image, region), ClearImage() | Draws an image in it, or a piece of one; draws none |
MoveTo(at) | Puts it at a place, as its left and top |
AddClass, RemoveClass, ToggleClass, HasClass | Its classes; see Classes |
Material | The material it is drawn with; see Elements drawn by a material |
Exists, Entity | Whether it is there, and the entity it is |
An element read before its document is shown, or one its document no longer has, does not exist: setting it throws.
Text that changes every frame
An interpolated string given to SetText is never made into a string. Each piece is written into a borrowed buffer, a number formatted where it goes, and the engine is given the text once. Text the element says already is no change, and nothing is laid out again.
Score.SetText($"Score: {score}");Timer.SetText($"{seconds:F1} s");SetText also takes a span of characters, or of UTF-8 bytes, for text you build yourself.
Classes
An element's classes are what a style sheet's .class selects (see Style sheets). Changing one restyles the element in the same frame, with the sheet's transitions, and makes no garbage:
Health.ToggleClass("low", hitPoints < 20); // on while low, off otherwiseCard.AddClass("picked");bool open = Door.ToggleClass("open"); // on where it was off, and says whichA class's name has no spaces.
Images and places
SetImage draws an image the game loaded or made with CreateImage (see Load assets from code), or a rectangle of it, in the image's pixels: an icon of a sheet of icons, a cell of an atlas. ImageRegion.At(x, y, width, height) makes one.
Icon.SetImage(sheet, ImageRegion.At(48 * column, 0, 48, 48));world.Ui.Pointer is where the pointer is over the game's picture, in the units documents are laid out in, or null off it. MoveTo puts an element there, as its left and top, for a sheet that places it absolutely: a stack carried under the pointer, or a tooltip.
if (World.Ui.Pointer is Vector2 at){ Carried.MoveTo(at + new Vector2(10, 10)); // just off the pointer's tip, so it covers no click}What these two set is drawn over the element's style sheets, as a script's style is on a web page: a card given its icon keeps it, and a rule that places the element gives way to MoveTo.
Elements drawn by a material
Material draws an element with a material running a UI shader (see Material). A material is shared by every element given it, so copy it first where one element should look different:
MaterialId bar = World.CopyMaterial(World.LoadMaterial(Addresses.Ui.Fill));World.SetFloat(bar, "fill", hitPoints / 100f);Health.Material = bar;A material of Bevy's own surface, which draws meshes, is refused.
Show and hide documents
A document is shown while the game plays by a UI Document in a scene, or opened from code:
ulong inventory = world.Ui.Open<InventoryScreen>(modal: true); // the game's maps off, the UI map onworld.Ui.Close(inventory);Open<T> shows the document whose class is T on an entity of its own, as a UI Document in a scene would, and gives that entity back. It is shown from the next frame, its class hearing OnShown() then. modal: true makes it a modal document (see Modal documents), and sortOrder: draws it above documents of a lower order. Open(id) opens one by its file's identity. Close takes it away, its class hearing OnHidden(); closing one already gone does nothing.
A document shown by a UI Document goes when the component goes or names another document, and every document goes as the game stops.
Panels in the world
Keys and a gamepad work a UI Panel once it is engaged. Submit engages the panel in front of the player while nothing is focused; a game whose UI map is off engages one by an action of its own:
ulong panel = world.Ui.PanelInFront;if (input.Pressed(Actions.Player.Interact) && panel != 0){ world.Ui.Engage(panel);}PanelInFront is the panel the middle of the screen looks at, or else the one seen nearest it, zero for none. Engage gives its first element focus and holds the game, the UI map on and the others off, until Cancel or world.Ui.Release() lets go of it; the panel's class hears OnCancel() for a Cancel. It returns false while a modal document is shown, or for a panel with nothing that can have focus. world.Ui.Engaged is the panel engaged now, zero for none.
Templates
Any document can be made inside another as the game plays: a card in a panel of cards, a row in a list. Add<T>() makes an instance of the document whose class is T under an element, after what is in it, and gives back the instance's own class:
partial class Inventory{ partial void OnAddClicked() { ItemCard card = Cards.Add<ItemCard>(); card.Show(Stock[_next++ % Stock.Length], this); }
partial void OnClearClicked() => Cards.Clear();}
partial class ItemCard{ partial void OnCardClicked() => _inventory?.Pick(this);
partial void OnDiscardClicked() => Remove();}Each instance has its own class, so a card's button is heard by the card it is on. From then on the instance is part of the document it was made in: reached by keys and a gamepad, held by a modal document as its own, and styled by the theme, that document's sheets, and then its own, so the outer document's sheet says where each card goes, .cards > .card, and a card's own rules reach nothing outside it.
Cards.Itemslists the instances made under an element, in order.card.Remove()takes one away, with what was made in it, its class hearingOnHidden().Cards.Clear()takes them all away.- Every instance goes with its document.
Every document of the game is loaded as it starts, so an instance is shown as it is made.
A template can also be placed in a document in the editor (see Templates: a document inside a document). Each instance placed is then a member of the outer class, typed as its template's class, which is made before the outer document's:
partial void OnShown(){ foreach (LevelButton level in (LevelButton[])[Level1, Level2, Level3]) { level.Chosen += Pick; // an event LevelButton's own half declares }}Bind elements to data
Bind keeps an element at what the game holds, typed, with no name in a string. The first function reads the value; the second, where given, is told what the player changed it to:
Volume.Bind(() => audio.Volume, value => audio.Volume = value); // a sliderQuality.Bind(() => settings.Quality, picked => settings.Quality = picked); // a dropdown, by its option's placeMusic.Bind(() => audio.Music, on => audio.Music = on); // a togglePlayerName.Bind(() => profile.Name, name => profile.Name = name); // a text field, a letter at a timeScore.Bind(() => $"Score: {score}"); // a labelEach binding reads its source between frames, after what the elements did is heard, and writes its element only where the value differs from what it last showed. So any field or property can be bound, with nothing to raise as it changes. An element has one binding: binding it again lets go of the one before, and Unbind() lets go of it, leaving the element as it is. A binding goes with its document.
A label's text binding makes a string each frame. For text that changes every frame, use SetText instead.
Dropdowns
A dropdown's options are written in the document, each its own element, so each can be localized. Code can give it options of its own instead, as a language menu does from the game's languages, and bind it to the place of the one picked:
partial void OnShown(){ Language[] languages = [.. World.Localization.Languages]; LanguageMenu.SetOptions(languages.Select(each => each.NativeName)); LanguageMenu.Bind( () => Array.IndexOf(languages, World.Localization.Language), picked => World.Localization.Language = languages[picked]);}SetOptions keeps the options it has, saying the new words, makes a copy of the first for each one more, and takes away the rest. The option picked stays where it is, or the last is picked where there are fewer. A slider binds to a whole number the same way, its value rounded as it is written.
A list
A panel bound to a list has one instance of a template under it for each item, in the list's order, made as items are added and taken away as they go:
Cards.Bind(items, (ItemCard card, Item item) => card.Show(item, this)); // items.Add makes a cardThe function shows a card its item once the card is shown. Items are told apart as their type tells two apart: a class by which object it is, a record by what it holds, and two alike by their order. A card taken away from code while its item is still in the list is made again, since the list says what is shown.
Settings kept between runs
World.Preferences.Use<T>() gives the one copy of a player's settings the game shares. Bound to it, an element saves the settings as the player lets go of it: a slider let go, a toggle turned, a letter typed. They are saved again as the game stops.
partial void OnShown(){ GameSettings settings = World.Preferences.Use<GameSettings>(); Music.Bind(() => settings.Music, on => settings.Music = on); Volume.Bind(() => settings.Volume, value => settings.Volume = value);}See Player preferences for how settings are declared and where they are kept.
Test a game's interface
A test presses an element as a click would, a button clicked or a toggle turned, heard on the next step:
menu.Play.SimulateClick();Keys, the mouse and gamepads are written in the same way; see Testing input.
In the Scripting API
- UiView: a document's class.
- UiElement: an element, its text, classes, image, value and bindings.
- GameUi:
world.Ui, documents opened, closed and found, and panels engaged. - UiEventKind: what an element can do.
- UiTextHandler and ImageRegion: text set without garbage, and a piece of an image.
