Show a value in my UI
The goal
Section titled “The goal”A label on your screen shows a value of the game, such as the player’s gold, and follows it when it changes.
Do it, step by step
Section titled “Do it, step by step”Without code
Section titled “Without code”- Make a TextMeshPro label on your canvas. It must be a
TMP_Text. - On the same object, choose Add Component > Intrigues > UI > Bound Text.
- Set Mode to Text. In Text, write the words with tokens in braces:
{player.Gold} gold. - Play. The label shows the value and follows it.
{player} is this machine’s player, so this line needs no Subject Source. {world} reads the world: {world.Date} is the date, and the World variables are members too.
For a clan, a scheme or a character, put a Subject Source on a panel above the label and write {this.Name}.
From code
Section titled “From code”IntrigueUI.Bind takes a text with tokens and a callback that receives the formatted text. Example, copied from section 6 of UI_GUIDE.md. Compiled against the package’s runtime assembly inside a MonoBehaviour with a TMP_Text goldLabel field; not run in Unity. You need using MrW.Intrigues; and using MrW.Intrigues.UI;.
UIBinding gold = IntrigueUI.Bind("{player.Gold} gold", IntrigueUI.Local, text => goldLabel.text = text);gold.SetText("{player.Gold} coins"); // another text through the same bindinggold.Dispose();The callback runs at the first flush, then only when the text differs from the last one shown. IntrigueUI.Local is the view that follows the player, and Bind also takes a TextContext, an Actor or a UISubject.
What you will see
Section titled “What you will see”The label redraws when the value changes, and when the player switches character.
In Play mode, the Bound Text Inspector shows a line, Now shows, with what the label has now.
What can go wrong
Section titled “What can go wrong”- The label shows the braces. A token that names nothing is printed as written, so a typo shows. The {this…} button lists the members that exist.
- The label is empty. A value that is not there reads as empty.
- The component shows a yellow box. Bound Text needs a TextMeshPro label on its object.
- No Gold value exists. The line assumes a character value called Gold, so use your own name.
- The code binding leaks. Call
Dispose()inOnDisable. A binding also ends by itself when its subject leaves the world. - A complex text is late. A text that goes through other objects or uses
{if}is formatted again at most every 0.25 seconds.
How it connects
Section titled “How it connects”- Components are on UI components, tokens on What you can write on a label, and more screens on UI recipes.
- The code door is on IntrigueUI from code.
- To read the same value in a script and not on a label, see Read Intrigues values from my code.