'Trying to get a InputField input as a Int in Unity

So basically, an user is gonna type in the hours in a inputfield and im gonna get the amount they write as an int in my code.

public InputField hours, minutes;
public int wantedHours, wantedMinutes;

Basically what i want is that people are gonna write a value in the inputfields. One of the inputfields is gonna be the "hours" you see in my code and the other one is gonna be "minutes". What i want is to get those inputfield inputs as "wantedHours" and "wantedMinutes" you see in my code.



Solution 1:[1]

First I'll set the input type validation to only get Integers, this way you avoid to check if the input is a letter or number.

Then you can get the string input value as: string wantedHoursString = hours.text If you want to parse that to an int variable you can do it with multiple ways with int.Parse or int.TryParse:

if(int.TryParse(hours.text, out int result))
{
    wantedHours = result;   
}
else
{
    Debug.Log($"Attempted conversion of {hours.text} failed");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1