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#?
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
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)
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class gemCounter : MonoBehaviour {
Player p;
//UnityEngine.UI.Text text;
public Text scoreText;
// Use this for initialization
void Start () {
p = GameObject.FindGameObjectWithTag ("Player").GetComponent<Player> ();
}
// Update is called once per frame
void Update () {
scoreText = "test";
}
}
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”;