Unity 2D: How to start the clock when the player loses all his life

advertisements

I want to start my timer countdown when my player's current health reaches 0. so far my timer is connected to my game over panel that slides down when the player loses all of his hearts (lives). When I play the application (game) the timer starts automatically and stops when my the game over panel slides down. Which is not what I want. What I want to do is make the timer start when the player loses all hearts (lives) and the game over panel slides down.

This is my player's health script:

public int curHealth;
public int maxHealth = 3;
Vector3 startPosition;
public PlayerHealth playerhealthRef;
float counter;
public Animator anima; // drag the panel in here again
private UI_ManagerScripts UIM;
private PandaScript ps;
DateTime currentDate;
DateTime oldDate;

void Start ()
{
    curHealth = maxHealth;
    startPosition = transform.position;
    ps = GameObject.FindGameObjectWithTag("PandaScript").GetComponent <PandaScript> ();
    currentDate = System.DateTime.Now;
}

void Update ()
{

    if (curHealth > maxHealth) {
        curHealth = maxHealth;
    }
    if (curHealth <= 0) {

        Die ();
    }
}

void Awake()
{
    UIM = GameObject.Find ("UIManager").GetComponent<UI_ManagerScripts> ();
}

void Die(){

    if (PlayerPrefs.HasKey ("Highscore")) {
        if (PlayerPrefs.GetInt ("Highscore") < ps.Score) {
            PlayerPrefs.SetInt ("Highscore", ps.Score);
        }
    } else
    {
        PlayerPrefs.SetInt ("Highscore", ps.Score);
    }

    UIM.EnableBoolAnimator(anima);
    PlayerPrefs.SetInt("RemainingLives", curHealth);
    print("Remanining Lives: " + curHealth);
    PlayerPrefs.Save();
}

void OnApplicationQuit()
{
    PlayerPrefs.SetString("sysString", System.DateTime.Now.ToBinary().ToString());
    print("Saving this date to prefs: " + System.DateTime.Now);
}

void LoadSaveData()
{
    PlayerPrefs.GetInt ("RemainingLives",0);
    OnApplicationQuit ();
}

public void Damage(int dmg)
{
    curHealth -= dmg;
    Reset();
}

void Reset ()
{
    transform.position = startPosition;
    GotoMouse.target = startPosition;

}
}

And this is my timer script:

public Text timer;
int minutes = 1;
int seconds = 0;
float miliseconds = 0;

public int curHealth;
public int maxHealth = 3;

[Range(1, 59)]
public int defaultStartMinutes = 1;
public bool allowTimerRestart = false;
public bool useElapsedTime = true;

private int savedSeconds;
private bool resetTimer = false;

private DateTime centuryBegin = new DateTime(2001, 1, 1);

void Start ()
{
    curHealth = maxHealth;
}

void Awake ()
{
    minutes = defaultStartMinutes;
    if (PlayerPrefs.HasKey("TimeOnExit"))
    {
        miliseconds = PlayerPrefs.GetFloat("TimeOnExit");
        savedSeconds = (int)miliseconds;

        if (useElapsedTime && PlayerPrefs.HasKey("CurrentTime"))
        {
            int elapsedTicks = (int)(DateTime.Now.Ticks / 10000000);
            int ct = PlayerPrefs.GetInt("CurrentTime", elapsedTicks);
            PlayerPrefs.DeleteKey("CurrentTime");
            elapsedTicks -= ct;
            if (elapsedTicks < miliseconds)
            {
                miliseconds -= elapsedTicks;
            }
            else
            {
                miliseconds = 0;
            }
        }

        minutes = (int)miliseconds / 60;
        miliseconds -= (minutes * 60);

        seconds = (int)miliseconds;
        miliseconds -= seconds;

        PlayerPrefs.DeleteKey("TimeOnExit");

    }
    savedSeconds = 0;
}

public void Update()
{
    // count down in seconds
    miliseconds += Time.deltaTime;
    if (resetTimer)
    {
        ResetTime();
    }
    if (miliseconds >= 1.0f)
    {
        miliseconds -= 1.0f;
        if ((seconds > 0) || (minutes > 0))
        {
            seconds--;
            if (seconds < 0)
            {
                seconds = 59;
                minutes--;
            }
        }
        else
        {
            resetTimer = allowTimerRestart;
        }
    }

    if (seconds != savedSeconds)
    {
        //  Show current time
        timer.text = string.Format("{0}:{1:D2}", minutes, seconds);
        savedSeconds = seconds;
    }
}

void ResetTime()
{
    minutes = defaultStartMinutes;
    seconds = 0;
    savedSeconds = 0;
    miliseconds = 1.0f - Time.deltaTime;
    resetTimer = false;
}

private void OnApplicationQuit()
{
    int numSeconds = ((minutes * 60) + seconds);
    if (numSeconds > 0)
    {
        miliseconds += numSeconds;
        PlayerPrefs.SetFloat("TimeOnExit", miliseconds);

        if (useElapsedTime)
        {
            int elapsedTicks = (int)(DateTime.Now.Ticks / 10000000);
            PlayerPrefs.SetInt("CurrentTime", elapsedTicks);
        }
    }
}
}


Use this free and very useful asset: https://www.assetstore.unity3d.com/en/#!/content/17276

Then write something like this:

Observable.EveryUpdate()
    .Where(_ => currentHealth <= 0)
    .Subscribe(_ =>
    {
        //Do something...
        //Ex. Die();
    });

All stuff in .Subscribe will do when condition in where return true. Use this in Start() not Update().

Ohhh... and if you want some simple timer, write for example:

Observable.Timer(TimeSpan.FromMilliseconds(1000))
    .Subscribe(_ =>
    {

    });