Search code examples
c#unity-game-enginetimercountdown

Timer stays at 0 during gameplay


screenshotI am currently adding a countdown timer to my unity game, however the actual numbers do not go down during game play but gradually go down within the inspector panel inside the "Time Left". Does anybody know why?

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

public class trackingclicks : MonoBehaviour {

    //static variable added to count users clicks
    //public static int totalclicks=0;
    //"mouseclick" keycode variable to look for mouse click
    public KeyCode mouseclick;
    public float timeLeft;
    public Text timerText;


    //public Transform scoreObj;

    // Use this for initialization
    void Start () {
        timerText.text = "Time Left:\n" + Mathf.RoundToInt (timeLeft);

    }

    void FixedUpdate () {
        timeLeft -= Time.deltaTime;
        if (timeLeft < 0) {
            timeLeft = 0;
        }

        timerText.text = "Time Left:\n" + Mathf.RoundToInt (timeLeft);
    }

    void UpdateText () {
        timerText.text = "Time Left:\n" + Mathf.RoundToInt (timeLeft);

    }
    // Update is called once per frame
    //void Update () {
    //checks the change in time, aka how much time has passed- bonus time starts at 90
        //clickcontrol.timeBonus -= Time.deltaTime;

        //if (clickcontrol.remainItems == 0) 
        //{
        //  clickcontrol.totalScore += (70 + (Mathf.RoundToInt(clickcontrol.timeBonus)));
            //scoreObj.GetComponent<TextMesh>().text = "Score : " + clickcontrol.totalScore;
            //clickcontrol.remainItems = -1;

        //}
    //Check for mouse click
    //if (Input.GetKeyDown (mouseclick)) 
        //{
        //  totalclicks += 1;

    //  }

    //  if (totalclicks >= 5) 
    //  {
    //      Debug.Log ("FAIL!!!");
        //  totalclicks = 0;

    //  }
    //}
}

Solution

  • When the Text component is created it's default VerticalOverflow value is Truncate.

    So, when you do:

    timerText.text = "Time Left:\n" + Mathf.RoundToInt (timeLeft);
    

    The "\n" will make Mathf.RoundToInt (timeLeft); to be written under "Time Left:". The text will not fit the TextBox when you do this.

    You have three options:

    1.Remove the "\n".

    2.Set the Text's VerticalOverflow to Truncate.

    This is all you need to do:

    timerText.verticalOverflow = VerticalWrapMode.Overflow;
    

    3.Decrease the Text font from 14 to about 13 or to a lower number.

    If you don't want to modify your Text so much then #2 should be used.

    EDIT:

    Make sure that the script is not attached to multiple GameObjects.

    Select the script, go to Assets --> Find References in Scene then remove the duplicated script from other objects.