I feel like there is something I’m missing but I don’t know why I can’t get my text in my canvas to display the time left float value. how do I fix this
CountDown.cs:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountDown : MonoBehaviour
{
float timeLeft = 300.0f;
Text text;
void Awake ()
{
text = GetComponent<text> ();
}
void Update()
{
timeLeft -= Time.deltaTime;
text.text = "time Left:" + timeLeft;
if(timeLeft < 0)
{
Application.LoadLevel("gameOver");
}
}
}
On line 13 you are using GetComponent(); but the actual component you are trying to find is a Text (notice the capital ‘T’ ).
It would be much easier for you though if you set your Text text to a public variable and then use the inspector to drag the reference of your UI Text into the script.
Here is a slightly modified version of your script that you can use to get a nice rounded integer countdown from 300. Let me know if you have any questions about it!
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountDown : MonoBehaviour
{
float timeLeft = 300.0f;
public Text text;
void Update()
{
timeLeft -= Time.deltaTime;
text.text = "Time Left:" + Mathf.Round(timeLeft);
if(timeLeft < 0)
{
Application.LoadLevel("gameOver");
}
}
}
public class Timercontroler : MonoBehaviour {
public Text timer;
float timeleft=300f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
timeleft -= Time.deltaTime;
int minute = Mathf.FloorToInt (timeleft / 60f);
int second = Mathf.FloorToInt (timeleft -minute*60);
timer.text = minute.ToString()+":"+second.ToString();
}
So this is the super basic timer I am currently working on. I am using it for a world space UI so… But hopefully it works for all of you guys.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CountDownTimer : MonoBehaviour {
public Text timerText;
[SerializeField] private float timeLimit = 10f;
private bool activeTimer = true;
private float t;
GameObject player;//reference to the player gameobject (not sure if needed)
PlayerHealth playerHealth;// reference to the health script
private void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
}
// Update is called once per frame
void Update() {
if (!activeTimer)
return;
t = timeLimit - Time.time;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
if (t <= 0)
{
TimeRanOut();
}