How can I display a variable (say an integer variable) in Unity's UI text? The variable may be a public variable from another script.
Can anyone please help me do it (step by step)?
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityHow can I display a variable (say an integer variable) in Unity's UI text? The variable may be a public variable from another script.
Can anyone please help me do it (step by step)?
Below is a script that will show the value myIntValue
, and only ever changes the value on screen when the value changes. Parts of this script will be integrated into whatever script is modifying your integer value. You'll then have a UI component somewhere else that has a Text
component on it. In the Unity editor, you'd drag the Text
component onto this script in the inspector. This will assign the Text
component to the textComponent
variable in the below script, which will then get updated when the your value changes.
public class DisplayValue : MonoBehaviour {
public Text textComponent;
private int myIntValue;
public int MyIntValue
{
get { return myIntValue; }
set
{
if(myIntValue != value)
{
//Here we're only updating the text shown on screen when the value is changed
myIntValue = value;
UpdateText(myIntValue);
}
}
}
void Awake () {
//If text hasn't been assigned, disable ourselves
if (textComponent == null)
{
Debug.Log("You must assign a text component!");
this.enabled = false;
return;
}
UpdateText(myIntValue);
}
void UpdateText (int value) {
//Update the text shown in the text component by setting the `text` variable
textComponent.text = "Value is: " + value;
}
}
Further, you can see a simpler version of this in the Unity tutorials on UI Text components
While the other answer explains how you can get your value to a text component, here is a way you can format the string. Instead of using something like
textComponent.text = "Value is: " + value;
as displayed in the other answer, you can use an interpolated string, using the $
, like such
textComponent.text = $"Value is: {value}";
Here is a bigger example:
int val;
void Start()
{
val = findObjectOfType<yourScriptName>().VariableName;
}
string name = "John";
string result = $"{name} is {val} years Old";