Skip to main content
Version: 0.4.1

Command box

A player types a command and presses Submit: help, hide, show, what or count. It's a small tour of the everyday C# that scripts can use:

  • a switch on the typed text, with two cases sharing one branch;
  • Count, a property that other scripts can read but only this script can change (private set), and Footer, a property worked out from other values (=>);
  • input?.text ?? fallbackText to read the input field when there is one, and ??= to set a value only the first time;
  • is and as to find out what kind of component the target is.

Set up: an input field, a TextMeshPro label, a button whose On Click calls SendCustomEvent("Submit") on this script, and optionally a Target, any component in your world.

CommandBox.cs
using StageTime.SDK;
using TMPro;
using UnityEngine;

/// <summary>
/// A small command box: type <c>help</c>, <c>hide</c>, <c>show</c>, <c>what</c> or <c>count</c> and press Submit.
/// Shows the everyday C# that scripts can use: properties, <c>switch</c> on strings, <c>?.</c>, <c>??</c> and
/// <c>??=</c>, and <c>is</c> / <c>as</c>. A Submit button calls <c>Submit</c> (On Click → SendCustomEvent).
/// </summary>
public class CommandBox : StageTimeBehaviour
{
public TMP_InputField input;
public TMP_Text label;

/// <summary>What <c>hide</c>, <c>show</c> and <c>what</c> act on (optional).</summary>
public Component target;

/// <summary>Text used when there is no input field (handy for testing).</summary>
public string fallbackText = "help";

/// <summary>How many commands ran. Other scripts can read it; only this script changes it.</summary>
public int Count { get; private set; }

private string greeting;
private string Footer => "(" + Count + " commands)";

public void Submit()
{
greeting ??= "Type a command.";
string text = input?.text ?? fallbackText;
Count++;
label.text = Run(text.Trim()) + " " + Footer;
}

private string Run(string command)
{
switch (command)
{
case "help":
return "Try: hide, show, what, count";
case "hide":
case "show":
if (target == null) return "Nothing to " + command;
target.gameObject.SetActive(command == "show");
return command == "show" ? "Shown" : "Hidden";
case "what":
return Describe();
case "count":
return "Count is " + Count;
case "":
return greeting;
default:
return "Unknown: " + command;
}
}

private string Describe()
{
if (target is null) return "Nothing set";
if (target is TMP_Text text) return "A text saying '" + text.text + "'";
if (target is Collider) return "A collider on " + target.name;
Transform asTransform = target as Transform;
return (asTransform?.name ?? "Something") + " is a transform";
}
}

switch on text is case-sensitive, like C#. See what scripts can use for the full list and the limits.