Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

retrieving Time from playerprefs and string format

Discussion in 'Scripting' started by unwshd_elend, Sep 12, 2020.

  1. unwshd_elend

    unwshd_elend

    Joined:
    Mar 21, 2019
    Posts:
    23
    Hello everyone,
    I really don't know whats wrong here,

    Code (CSharp):
    1.   public static void SaveOnShutDown()
    2.     {
    3.         Debug.Log("__SAVING");
    4.  
    5.  
    6.         PlayerPrefs.SetString("LastShutdownTime" , DateTime.Now.ToBinary().ToString());
    7.    
    8.  
    9.         SavePlayer(PlayerData.instance.GetData());
    10.     }
    11.  
    12.     public static long LoadOnStartUp()
    13.     {
    14.         Debug.Log("__LOADING");
    15.  
    16.      
    17.  
    18.  
    19.  
    20.  
    21.         long tempTime = Convert.ToInt64(PlayerPrefs.GetString("LastShutdownTime"));
    22.         DateTime offlineTime = DateTime.FromBinary(tempTime);
    23.         TimeSpan difference = DateTime.Now.Subtract(offlineTime);
    24.         long rawtimeTotalSeconds = (long) difference.TotalSeconds;
    25.         return rawtimeTotalSeconds;
    26.  
    27.     }
    28.  
    everything works fine in the editor
    but in my android build i get this string format error :


    AndroidPlayer(ADB@127.0.0.1:34999) FormatException: Input string was not in a correct format.
    at System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) [0x00057] in <4756199cf52a4f14b33cdcc5659f782e>:0
    at System.Number.ParseInt64 (System.String value, System.Globalization.NumberStyles options, System.Globalization.NumberFormatInfo numfmt) [0x00014] in <4756199cf52a4f14b33cdcc5659f782e>:0
    at System.Int64.Parse (System.String s, System.IFormatProvider provider) [0x00008] in <4756199cf52a4f14b33cdcc5659f782e>:0
    at System.Convert.ToInt64 (System.String value) [0x0000c] in <4756199cf52a4f14b33cdcc5659f782e>:0


    which happens at line :
    long tempTime = Convert.ToInt64(PlayerPrefs.GetString("LastShutdownTime"));

    ...

    please help !
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    The first time you run this,
    PlayerPrefs.GetString()
    is going to return a null or empty string (docs say which, I forget, does not matter really).

    That can't be converted to a
    long
    , hence the error above.

    Instead use
    System.Int64.TryParse()
    to have a chance of parsing it and using a default value (probably of current time?) if it can't parse it:

    https://docs.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=netcore-3.1
     
    unwshd_elend likes this.