Score input
A player types a score into an input field and presses Submit. int.TryParse reads the text without crashing the
script on bad input, and TryReadScore is a method of the script that gives back two extra values with out: the
score and, when it's rejected, the reason. out _ ignores a value you don't need.
Set up: an input field, a TextMeshPro label and a button whose On Click calls SendCustomEvent("Submit") on this
script.
ScoreInput.cs
using StageTime.SDK;
using TMPro;
/// <summary>
/// Reads a score typed into an input field and shows it, or why it was rejected. Shows <c>out</c> parameters: the
/// SDK's <c>int.TryParse</c> and <c>float.TryParse</c>, and a script method that returns two extra values.
/// A Submit button calls <c>Submit</c> (On Click → SendCustomEvent).
/// </summary>
public class ScoreInput : StageTimeBehaviour
{
public TMP_InputField input;
public TMP_Text label;
/// <summary>Text used when there is no input field (handy for testing).</summary>
public string fallbackText = "42";
public void Submit()
{
string text = input != null ? input.text : fallbackText;
if (TryReadScore(text, out int score, out string problem))
{
label.text = "Score: " + score;
}
else if (!int.TryParse(text, out _) && float.TryParse(text, out float decimalValue))
{
label.text = "Whole numbers only (got " + decimalValue.ToString("0.##") + ")";
}
else
{
label.text = problem;
}
}
/// <summary>True with the score when <paramref name="text"/> is a whole number from 0 to 1000.</summary>
private bool TryReadScore(string text, out int score, out string problem)
{
problem = "";
if (!int.TryParse(text, out score))
{
problem = "Not a number: " + text;
return false;
}
if (score < 0 || score > 1000)
{
problem = "Scores go from 0 to 1000";
return false;
}
return true;
}
}
out and ref work in calls to your own methods and to SDK methods such as int.TryParse, float.TryParse and
STPhysics.TryRaycast. Other scripts can't call a method that has out or ref
parameters; give them a method that returns a value instead.