MMT - ElectriX
MMT - ElectriX

Reputation: 17

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.

Upvotes: 0

Views: 4314

Answers (2)

borodatych
borodatych

Reputation: 316

In editor for InputField set ContentType as Integer: enter image description here

Use in Code:

public void SetScore(InputField input)
{
    int score = int.Parse(input.text);
    GameManager.SetScore(score);
}

Upvotes: 0

Lotan
Lotan

Reputation: 4283

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");
}

Upvotes: 0

Related Questions