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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

UI Text in C#

Discussion in 'UGUI & TextMesh Pro' started by FirefIy, May 3, 2015.

  1. FirefIy

    FirefIy

    Joined:
    Apr 15, 2015
    Posts:
    23
    Guys, I'm having huge issues with adding GUI text into the screen. Yes I know that I can simple Create new -> UI -> Text. But how do I change the text using a C# script? I have a score that has to be updated, but I dont know which function to call. If I try to google I only find old versions of doing this in JS and they no longer work. How to do it in Unity 5.0.1 using C#?

    Help please!
     
  2. Raimis

    Raimis

    Joined:
    Aug 27, 2014
    Posts:
    160
    1) Create a public or (private + serializable flag) variable in your component code "public Text scoreText". Drag a reference in hierarchy to link these components. Then use scoreText.text in your code. Hope this helps
     
    Kiwasi likes this.
  3. FirefIy

    FirefIy

    Joined:
    Apr 15, 2015
    Posts:
    23
    How do I use it?
    It gives me an error.
    c:\Users\Aleksei\Dropbox\purpura_draco\Assets\Script\gemCounter.cs(15,15): Error CS0029: Cannot implicitly convert type 'string' to 'UnityEngine.UI.Text' (CS0029) (Assembly-CSharp)
     
  4. FirefIy

    FirefIy

    Joined:
    Apr 15, 2015
    Posts:
    23
    code
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5.  
    6. public class gemCounter : MonoBehaviour {
    7.     Player p;
    8.     //UnityEngine.UI.Text text;
    9.     public Text scoreText;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.         p = GameObject.FindGameObjectWithTag ("Player").GetComponent<Player> ();
    14.    
    15.    
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update () {
    20.  
    21.         scoreText = "test";
    22.    
    23.     }
    24. }
    25.  
     
  5. OldManAnimal

    OldManAnimal

    Joined:
    Jul 10, 2014
    Posts:
    45
    It's confusing but the Text component object has a string variable named 'text' that you have to access. So instead of scoreText = "test"; you would have to do scoreText.text = "test";
     
    FirefIy and Kiwasi like this.