How to convert string into int in unity C#

 We can use int.Parse() or int.TryParse() method for converting a string into int in unity as we use regular C# language. here is an example of  int.Parse() :

Code :
string input = "123";
int result = int.Parse(input);
Debug.Log(result); // Output: 123

convert string into int in unity C#


Example of int.TryParse()  given below: 
Code :
string input = "123";
int result;
bool success = int.TryParse(input, out result);
if (success)
{
    Debug.Log(result); // Output: 123
}
else
{
    Debug.Log("Invalid input");
}

int.TryParse(input, out result)  is a safer method because we can check if a given string is actually a int or not so we can minimize some exception errors.

Additionally, We can also use Convert.ToInt32() method to convert a string into into, example of Convert.ToInt32() is given below:
Code :
string input = "123";
int result = Convert.ToInt32(input);
Debug.Log(result); // Output: 123
an exception will we throw by this method if string is not a integer. you can use any of the above method according to your requirement.


Comments