Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to use Convert.Int64 in unity3D

Discussion in 'Scripting' started by MG, Sep 24, 2017.

  1. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Hello

    I'm working on a game where I want to use the type of ulong.

    I'm trying to store my ulong variable in a string.

    I do know how to go from ulong to string, by simple using .ToString();

    But I really dont know how to do it from string to uLong.

    I have been reading up on Convert.Int64, but it doesn't recognize it.

    Code (CSharp):
    1. string CurrentMoneyAsString = PlayerPrefs.GetString("Money");
    2.         long CurrentMoneyAsUlong = Convert.Int64(CurrentMoneyAsString);
    I'm getting the error

    What do i do?
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Convert is part of the System namespace, unless you're referring to a different type.
    Also, it only defines the methods using the format ToXYZ, e.g. ToInt64(...).

    You either wanna make sure to use the FQN (given that x is a value of a type matching an overload of the method):

    Code (csharp):
    1. ... = System.Convert.ToInt64(x);
    or add the using directive at the top, and use it like this:

    Code (csharp):
    1. // top of your script
    2. using System;
    3.  
    4. // later in code
    5. ... = Convert.ToInt64(x);
    6.  

    Additional note:
    While this is a working solution and can be used with care, i.e. as long as you have full control over the string to convert back and forth, there is a more robust/defensive strategy to convert/parse the value, which should primarily be used whenever you're not in full control of the value:

    Code (CSharp):
    1. if (long.TryParse(x))
    2. {
    3.     // parsing succeeded
    4. }
    5. else
    6. {
    7.     // parsing failed, handle situation
    8. }
     
    Last edited: Sep 24, 2017
    projectsolushq and MG like this.
  3. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Suddoha Thank you man! It freaking works! Love ya bro!