Hi. I want to use GUI Text to display a score, but it needs to change. Can I please have a basic code snippet to change the displayed text from a variable?
Thanks!
Hi. I want to use GUI Text to display a score, but it needs to change. Can I please have a basic code snippet to change the displayed text from a variable?
Thanks!
Check out the docs for GUI Text. You'll specifically be interested in the text variable of a GUI Text.
First put using UnityEngine.UI; then do the following and attach this script to UI TEXT Control.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DisplayScore : MonoBehaviour {
Text txt;
private int currentscore=0;
// Use this for initialization
void Start () {
txt = gameObject.GetComponent<Text>();
txt.text="Score : " + currentscore;
}
// Update is called once per frame
void Update () {
txt.text="Score : " + currentscore;
currentscore = PlayerPrefs.GetInt("TOTALSCORE");
PlayerPrefs.SetInt("SHOWSTARTSCORE",currentscore);
}
}
Like Elliot said:
guiText.text = "New Text";
You didn't tell us what language you use, but fortunately this line is the same in JS or C# (i guess you don't use Boo? right?) ;)
edit
To change the GUIText of another GameObject you can put a public variable at the top of your script and drag the desired GameObject/GUIText onto the variable in the inspector.
// JS
var targetGuiText : GUIText;
function Start()
{
targetGuiText.text = "Hey ya!";
}
To find the GUIText object, you can also use GameObject.Find, like so:
guiText = GameObject.Find("GUI_TEXT_NAME").guiText;
For effieciency, do this in the Start()
function and save it to a private GUIText
variable.
As of Unity 2.0, you can also use the GUI.Label function.
Here what I used. I tried a few other methods that gave me some issues, this seems to work great with the yourText GUI Text Object dragged into the inspector:
public class WhateverScript : MonoBehaviour {
public GUIText yourText;
void Update (){
yourText.text = "Coins " + currentCoins + "/" + maxCoins;
The old UI has been decomissioned.
New tutorial Recorded Video Sessions on UI - Unity Learn
However is does not show how to assign dynamically value to the text only explains how to use Richtext editor.
As said by gregolio, there is a new UI system.
Here is a tutorial who explains how to change dynamically text (from 2:50): Tutorial ui-text