About Time.time.

Hello everyone,

I have a stopwatch in one scene (stage_A) of my game when I start the scene (menu) the timer in this scene (stage_A) starts counting and I am unable to find out why, I wanted him begins to count only when the scene (stage_A) is loaded:

script stage_A on Main Camera;

public Text stopwatch;

void Update () 
{
 if(Application.loadLevel != 1)
   return;

  //Display format 00:00
  secs = (int)(Time.time % 60);
  mins = (int)(Time.time / 60);
 
 stopwatch.text = string.Format("{0:00}:{1:00}", mins, secs);
}

script Menu:

public void Play()
{
   StartGame.current = new StartGame();
   StartGame.current.Character.name = name;
   SaveLoad.Save();
   Application.LoadLevel("stageA");   
}

in build settings the index scene menu is 0 and scene stage_A is 1.

Thank’s!!

Time.time counts time from the start of the game, there’s no way to tell it to count from the level load. Unity - Scripting API: Time.time

Set a script on stage_A and on Start(). On the script’s Start() set a variable startTime equal to Time.time.

In the stopwatch Update() method subtract startTime from Time.time and set that to be the text.

Alternatively you can use Time.timeSinceLevelLoad Unity - Scripting API: Time.timeSinceLevelLoad

As far as I know Time.time starts at the start of the game. If you want time since the start of the Scene, you can remember time at start of the scene and subtract from current time, or you some different counter.

Hello, I tried this solution more found a bug, when the score reached 00:57 jumped to 01:-03 and subtract to return to 01:00 and then he went along counting 01:01, 02 etc, this was my solution:

 timer += Time.deltaTime;

 mins = Mathf.FloorToInt(timer / 60F);
 secs = Mathf.FloorToInt(timer - mins * 60);
 stopwatch.text = string.Format("{0:00}:{1:00}", mins, secs);

The script can’t run if it’s not active in an object on the loaded scene, but I guess you’re confused on how Time.time works. From the docs: “The time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game.”

If you use Time.time in any scene you’ll always get the time elapsed since the program started, if you want a timer that starts at 0 when loading a scene you have to count the elapsed time since the object was loaded, or register the time it was loaded and substract that time from the current Time.time every time you need the value. Counting the elapsed time gives you more control (you can stop a timer and continue later), the basic logic would be:

private float elapsedTime = 0f;

void Update () {
    elapsedTime += Time.deltaTime; //increment the elapsedTime with the duration of the last frame

    //Display format 00:00
    secs = (int)(elapsedTime % 60);
    mins = (int)(elapsedTime / 60);
  
    stopwatch.text = string.Format("{0:00}:{1:00}", mins, secs);
}