Timer countdown C #

1

Hi, I'm doing a game in Unity which must have a chronometer that starts at 60, when it reaches 30 it should change the color of the letters to red and when it reaches 0 it should start to increase and not go to negative until now I have the initial count but I can not do the second part that the chronometer is returned.

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

 public class Timmer : MonoBehaviour {

     public Text Tempo; 
     public float tiempo = 0.0f;



     // Update is called once per frame
     void Update () {
         tiempo -= Time.deltaTime;
         Tempo.text = "Tiempo:" + " " + tiempo.ToString ("f0");

     }
 }
    
asked by Nicolas Rudisky 02.08.2016 в 16:06
source

1 answer

4

I do not work with Unity so often, but you can implement a vague solution like the following:

public class Timmer : MonoBehaviour 
{
    public Text Tempo;
    public float Tiempo = 0.0f;
    public bool DebeAumentar = false;

    void Update() 
    {
        if (DebeAumentar) 
            Tiempo += Time.deltaTime; 
            // Primero se comprueba que sea falso el tener que aumentar.
        else 
        {
            if (Tiempo <= 0.0f)  // Comprueba si es menor o igual a cero.
            { DebeAumentar = true; } // Para volver true a este.
            else 
            { Tiempo -= Time.deltaTime; } // De lo contrario, sigue bajando.
        }
        if (Tiempo <= 30.0f) 
        { Tempo.color = Color.Red; } // Comprueba para cambiar el color del text. 
        else { Tempo.color = Color.Green; } // Vuelve a verde cuando aumente...

        Tempo.text = "Tiempo:" + " " + Tiempo.ToString ("f0");
    }
}

For something simple it should work, you can also improve the code, it is well explained in comments.

EDIT : I have made a small improvement in the code to improve its readability, but I do not know if it will be compatible with your version of C #, I have tried it in C # 6:

public class Timmer : MonoBehaviour
{
    public Text Tempo;
    public float Tiempo = 0.0f;
    public bool DebeAumentar = false;

    void Update()
    {
        // Se comprueba si debe aumentar el valor primero...
        DebeAumentar = (Tiempo <= 0.0f)  ? true : false;

        // Luego se efectua el aumento.
        if (DebeAumentar) Tiempo += Time.deltaTime;
        else Tiempo -= Time.deltaTime;

        // Se asigna el color dependiendo del tiempo restante.
        Tempo.color  = (Tiempo <= 30.0f) ? Color.Red : Color.Green;

        Tempo.text = "Tiempo:" + " " + Tiempo.ToString ("f0");
    }
}

It should work in the same or better way.

I have to use the ternario operator in this second implementation and it is represented in the following way:

Var = (Condición) ? (Si cumple la condición, se asigna este valor) : (De lo contrario, este);

It's something like a "Conditional Assignment" . I hope you help.

    
answered by 02.08.2016 / 16:30
source