GUIText in Unity 5 (Need an alternative)

3.3k views Asked by At

I've been following a tutorial on how to make a timer on YouTube but I am now stuck because of the GUIText problem in Unity 5. This is my code:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Timer : MonoBehaviour {

    public float Seconds = 59;
    public float Minutes = 0;

    void Update() {

        if (Seconds <= 0) {

            Seconds = 59;
            if (Minutes > 1) {

                Minutes--;

            } else {

                Minutes = 0;
                Seconds = 0;
                //This makes the guiText show the time as X:XX. ToString.("f0") formats it so there is no decimal place.
                GameObject.Find("TimerText").GUIText.text = Minutes.ToString("f0") + ":0" + Seconds.ToString("f0");

            }

        } else {

            Seconds -= Time.deltaTime;

        }

        //These lines will make sure that the time is shown as X:XX and not X:XX.XXXXXX
        if(Mathf.Round(Seconds) <= 9) {

            GameObject.Find("TimerText").GUIText.text = Minutes.ToString("f0") + ":0" + Seconds.ToString("f0");

        } else {

            GameObject.Find("TimerText").GUIText.text = Minutes.ToString("f0") + ":" + Seconds.ToString("f0");

        }

    }

}

The problem is with the GUIText.

error CS1061: Type 'UnityEngine.GameObject' does not contain a definition for 'GUIText' and no extension method 'GUIText' of type 'UnityEngine.GameObject' could be found (are you missing a using directive or an assembly reference?)

What can I do to make the timer show in my game without the GUIText?

2

There are 2 answers

1
Alex Sikilinda On BEST ANSWER

Instead of doing GameObject.Find("TimerText").GUIText.text, you can rewrite it using GetComponent(string) method, which is the right way:

GameObject.Find("TimerText").GetComponent<GUIText>().text = 
    Minutes.ToString("f0") + ":0" + Seconds.ToString("f0");
3
dev-masih On

Simply select your Gameobject that you assigned this code to it and in Inspector view click on Add Component and add GUI Text component to it.
don't forget to set the Font for it