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. Dismiss Notice

Question tryparse returning 0

Discussion in 'Scripting' started by melonhead, Aug 16, 2023.

  1. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    603
    have i got the idea of tryparse wrong, i am trying to convert an int to string then back to int but it only returns 0, anyone got any idea how this works, i need the converted int to match the original int after conversion

    code below thanks
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class INTTOHEXCHECK2 : MonoBehaviour {
    6.  
    7.  
    8.     public int Score;
    9.  
    10.     private int myNewInt;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.  
    15.  
    16.         string myHex = Score.ToString("X");
    17.  
    18.  
    19.         int.TryParse(myHex, out myNewInt);   //  ONLY RESULTS CONVERTING TO 0
    20.  
    21.  
    22.         Debug.Log("Score "+ Score + "   HEX "+ myHex + "   BACKTOINT "+ myNewInt);
    23.  
    24.  
    25.  
    26.        
    27.        
    28.     }
    29.    
    30.  
    31. }
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,991
    you are converting to hexadecimal, it might contain letters. (then int parse fails).
    try printing out the "myHex" to check,
    also int.TryParse() returns true or false, can check that too.

    or look for code to convert hex value into integer.

    why you need to convert int to string and back?
     
    Bunny83 likes this.
  3. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,048
    Bunny83 and wideeyenow_unity like this.
  4. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    603
    codesmile thanks, but getting error "
    The name `Int32' does not exist in the current context

    am i missing a using directive at top of script?
     
  5. bugfinders

    bugfinders

    Joined:
    Jul 5, 2018
    Posts:
    753
    if you know its hex you could write your own.... do it character by character
     
  6. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,048
    Just prefix it with System.Int32 or change Int32 to int. These are synonymous.
     
  7. melonhead

    melonhead

    Joined:
    Jun 3, 2014
    Posts:
    603
    thanks works like a charm, regards