- Home /
Convert string to int C#
I have some problem with my login. My login is so simple. User type name and then that name will be show up when it play. In my script I have some problem with convert string to int. I use playerprefs for saving that name, but playerprefs doesnt wont to saving the name. Please help me. I have to finished this task in 1 week.
This is my script
bool player1 = false; bool player2 = false;
public static string EditPlayer1 = "";
public static string EditPlayer2 = "";
public static int IntEditPlayer1;
public static int IntEditPlayer2;
GUIStyle myFont;
void start (){
myFont = new GUIStyle ();
myFont.fontSize= 12;
}
void OnGUI() {
Event e = Event.current;
if (e.keyCode == KeyCode.Return)
player1 = true;
else if (false == player1)
EditPlayer1 = GUI.TextField (new Rect (450, 230, 300, 50), EditPlayer1,200);
IntEditPlayer1 = System.Int32.TryParse(EditPlayer1); <<< ERROR
PlayerPrefs.SetInt ("Player1", IntEditPlayer1);
if (e.keyCode == KeyCode.Return)
player2 = true;
else if (false == player2)
EditPlayer2 = GUI.TextField (new Rect (450, 310, 300, 50), EditPlayer2,200);
IntEditPlayer2 = System.Int32.TryParse (EditPlayer2); <<< ERROR
PlayerPrefs.SetInt ("Player2", IntEditPlayer2);
}
void Update(){
Debug.Log ("EditUser"+EditPlayer1);
}
What error do you get on the lines specified with '<<< ERROR' ?
Answer by robertbu · Jul 03, 2014 at 06:32 AM
I use TryParse() when I don't need or want to deal with exception handling, but you still have to use it correctly...and you still need to figure out what to do if the conversion failed. It returns a boolean value indicating the success of the converstion. For your code it will be something like this:
if (!System.Int32.TryParse (EditPlayer2, out IntEditPlayer2) {
// Error handling goes here
}
Your answer
Follow this Question
Related Questions
Convert Text to float 3 Answers
Converting a string to an int 2 Answers
Convert Array to String 3 Answers
How to convert a list of Resolution to String 2 Answers
string + int = variable 2 Answers