Source file unity-csharp/arcade-classics/shared/ArcadeHud.cs from the GDnD code examples. Download raw file
// GDnD wiki example
// Demonstrates: a minimal non-diegetic HUD — a persistent status line plus a timed centre message — drawn with TextMeshPro on a Screen Space - Overlay Canvas
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[ui-design]], [[game-interface-types]]
using TMPro;
using UnityEngine;
// Shared by all eight arcade-classics examples (copy this file alongside each
// game's scripts). The game controller owns the numbers; this component only
// displays them. Keeping display separate from game state means the controller
// never needs to know how the HUD is drawn, and the HUD never changes the rules.
public class ArcadeHud : MonoBehaviour
{
[Tooltip("Persistent readout such as score and lives. Anchor it to a screen corner.")]
[SerializeField] private TMP_Text statusText;
[Tooltip("Short-lived banner such as \"Game over\". Anchor it to the screen centre.")]
[SerializeField] private TMP_Text messageText;
[SerializeField] private float messageSeconds = 2.5f;
private float messageTimer;
private void Awake()
{
// Clear the placeholder "New Text" so nothing shows until the game speaks.
if (messageText != null)
{
messageText.text = string.Empty;
}
}
private void Update()
{
if (messageTimer <= 0f)
{
return;
}
messageTimer -= Time.deltaTime;
if (messageTimer <= 0f)
{
messageText.text = string.Empty;
}
}
public void SetStatus(string text)
{
if (statusText != null)
{
statusText.text = text;
}
}
// Shows a message for messageSeconds; a newer message replaces an older one.
// With no message text assigned, it falls back to the Console.
public void ShowMessage(string text)
{
if (messageText == null)
{
Debug.Log(text);
return;
}
messageText.text = text;
messageTimer = messageSeconds;
}
}