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
?
Instead of doing
GameObject.Find("TimerText").GUIText.text
, you can rewrite it usingGetComponent(string)
method, which is the right way: