Trying to Get The Total Time of a Gameplay

Hello, please help!
I’m trying to get the total time of a gameplay, but I don’t know what’s wrong…
The purpose is to start getting the time if the user hits Return and printing the time in hours when hits Space.

P.S: Sorry for my bad english :stuck_out_tongue:

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

public class CalculaTempoScript : MonoBehaviour {

    public bool i = true;
    private float timePassedSecs;
    private int timePassedHours;

    void Update () {
        CalcTime ();
    }

    void CalcTime () {
        if (Input.GetKey(KeyCode.Return)) {
            while (i == true) {   
                timePassedSecs = Time.deltaTime;
                Debug.Log (timePassedSecs);
                if (Input.GetKey(KeyCode.Space)) {
                    i = false;
                    timePassedSecs = timePassedSecs / 3600f;
                    timePassedHours = (int)timePassedSecs;
                    Debug.Log ("A partida durou: " + timePassedHours);
                }
            }
        }
    }
}

your while loop is wrong cause you won’t get the space event and so looping forever.

1 Like

You can try something like this:

private float start;
    private bool alreadyPressed = false;
    void calcTime()
    {
        if (Input.GetKey(KeyCode.Return))
        {
            start = Time.time;
            alreadyPressed = true;
        }
        else if(Input.GetKey(KeyCode.Space) && alreadyPressed)
        {
            alreadyPressed = false;
            Debug.Log("Total time in second: " + Time.time - start);
        }
    }
1 Like

:slight_smile: (Think you read it too fast. )

I did indeed.