Search Unity

Timer Troubles: "Difference" Discrepancy

Discussion in 'Scripting' started by krougeau, Aug 1, 2015.

  1. krougeau

    krougeau

    Joined:
    Jul 1, 2012
    Posts:
    456
    I've working on setting up an "offline" timer for my game, and while things are close to working correctly, I find that the count is off by as little as 15 seconds and as much as 90 seconds, seemingly randomly, when I log off and back on. The timer works perfectly while in-game, so the discrepancy must be in the calculations when I come back online.

    I have a function setup to store the current DateTime.Now to a variable called "then" when the player loses a life. I then create a new variable called "difference" which subtracts "then" from the current DateTime.Now, "now", until the difference is equal or greater to my "wait" time (in seconds). If the user logs off, "then" is stored offline as a string and then converted back when the user logs on, at which point the countdown continues.

    I'm sure that there's some minor misstep in my math and was wondering if any of you could tell me just where I've gone awry? I'm including a watered down version of the code below for your consideration. Any assistance would most certainly be appreciated. Thanks! (Again, this is a simplified version of my actual script, just to show the basic math at work.)

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System;
    4. using System.Collections;
    5.  
    6. public class Timer : MonoBehaviour
    7. {
    8.     public Text timeTxt;
    9.     private DateTime now;
    10.     private DateTime then;
    11.     private TimeSpan difference;
    12.     private int waitSecs = 1800;
    13.     private int timer;
    14.     private int min;
    15.     private int sec;
    16.     private bool counting = false;
    17.  
    18.     // called from my Game Manager script when the user is logged in
    19.     void CalcDifference()
    20.     {
    21.         // pulled from the backend database, but you get the idea
    22.         then = Convert.ToDateTime(response.ScriptData.GetString("time"));
    23.         counting = true;
    24.     }
    25.  
    26.     void Update()
    27.     {
    28.         if(counting == true)
    29.         {
    30.             now = DateTime.Now;
    31.             difference = now.Subtract(then);
    32.             // a few variables for displaying the timer GUI
    33.             timer = waitSecs - (int)((float)difference.TotalSeconds);
    34.             min = timer / 60;
    35.             sec = timer % 60;
    36.             timeTxt.text = String.Format("{0:00}:{1:00}", min, sec);
    37.             if(difference.TotalSeconds >= waitSecs)
    38.             {
    39.                 counting = false;
    40.             }
    41.         }
    42.     }
    43. }
     
    Last edited: Aug 1, 2015