-1
\$\begingroup\$

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)?

\$\endgroup\$
1
  • \$\begingroup\$ It sounds like you should work your way through some beginners' tutorials. Displaying a value in UI - like a score counter, timer, or health value - is a very common task that's covered extensively in existing resources. If you run into a particular problem following these tutorials, that's the kind of thing more personalized channels like our Q&A site can help with. \$\endgroup\$
    – DMGregory
    Jun 26 '18 at 13:37
1
\$\begingroup\$

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

\$\endgroup\$
-1
\$\begingroup\$

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";
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.