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 https://learn.unity.com/tutorial/set-up-your-first-project-in-unity?uv=2020.3&pathwayId=5f7e17e1edbc2a5ec21a20af&missionId=5f71fe63edbc2a00200e9de0&projectId=5caccdfbedbc2a3cef0efe63#5cb7a1acedbc2a10b7261d16

Just about 7 years after the post was created
very timely

2 Likes

But still helped me ;)

1 Like