Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to display a variable value on screen?

Discussion in 'UGUI & TextMesh Pro' started by angel_m, Nov 28, 2014.

  1. angel_m

    angel_m

    Joined:
    Nov 4, 2005
    Posts:
    1,160
    I have installed Unity 4.6 and I have read the docs but I haven't found any explanation about how to display a variable value (a counter, for example) on screen with the new UI.
    Sorry if it is a silly question but the part about Text (label) only refers to the string being displayed. I assume the variables are referenced by code. Is this correct?
    Thanks
     
  2. the_motionblur

    the_motionblur

    Joined:
    Mar 4, 2008
    Posts:
    1,774
    First and foremost you need a Text object on the canvas where you want to print the text.

    Then you can reference to this text by code.
    Let's say you want to display a score counter. There are a few things to remember.
    The most important one is if you want to access UI by script youo need to include "using UnityEngine.UI;" otherwise you can't acces any of the new UI functions by code.
    Then you can create a Text object which you can reference to by Text.text = "yourTextHere";

    So it might look something like this:
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;  // IMPORTANT!!!!!!!!
    5.  
    6. public class ScoreCounter : MonoBehaviour {
    7.  
    8.     public Text scoreText;  // public if you want to drag your text object in there manually
    9.     int scoreCounter;
    10.  
    11.     void Start () {
    12.         scoreText = GetComponent<Text>();  // if you want to reference it by code - tag it if you have several texts
    13.     }
    14.  
    15.     void Update () {
    16.         scoreText.text = scoreCounter.ToString();  // make it a string to output to the Text object
    17.     }
    18. }
    19.  

    (edit) sorry - found a typo on my code. it's scoreText.text, of course.
     
    Last edited: Nov 28, 2014
  3. idk_or_smt125653

    idk_or_smt125653

    Joined:
    Mar 3, 2022
    Posts:
    2
    this ones the typo