how to display a text on the screen

i want to be able to display a text on the screen like points or health…

Add a UI text to your scene. You’ll find it under the GameObject/UI/Text menu. Read more in the manual.

2 Likes

ok but how do i set the text to display the variable

1 Like

Here’s a simple example:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextTest : MonoBehaviour {
    public Text myText;

    int test = 0;

    void Update () {
        myText.text = test.ToString();

        test++;
    }
}
4 Likes

If you

you would see that there is a text property on the UI text component. You need a reference to that component in the script that wants to set it then you can simply do…

Text t;
int health;

// lots and lots other other code and stuff ....

// in a method somehere where you need to do the stuff..
t.text = health.ToString();

How you set t and health is dependent on your code… Also make sure to set the text expansion properties to overflow horizontal and vertical or it will disappear if the number is too long.

2 Likes

thx

1 Like

there is an error in this code,i can’t see what it is,i have done what you guys said.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class checkifclick2 : MonoBehaviour {
    public static int points = 0;
    public Text MyText;
    void OnMouseDown () {
        Destroy(gameObject);
        points = points + 1;
    }
    void Update() {
        MyText.text = points.ToString ();
        points++;
    }
}
2 Likes

If you want this to work the display text code needs to be on an object that isn’t destroyed.

Go do Roll A Ball. It has a good section on displaying text.

2 Likes

K go here to find good tutorials it might help with ur problems Lesson 1.1 - Start your 3D Engines - Unity Learn

Just about 7 years after the post was created
very timely

2 Likes

But still helped me :wink:

1 Like