Converting String to Integer error

Hello.

I am trying to convert a string to an integer from a TMP input field. I have tried using TryParse and am currently trying to use Parse, though it is not working.
I keep receiving this error: error CS0029: Cannot implicitly convert type ‘int’ to ‘string’

[SerializeField] private string inputWidth;

public void GrabFromInputField (string input)
    {
        inputWidth = int.Parse(input);
    }

Thank you!

Shouldn’t your inputWidth field be an integer? You’re trying to convert a string to an int, but still trying to assign it to another string variable.

2 Likes

The Parse method takes a string input and has an int output. In your code you are giving it a string named input as input and you try to assign the result to another string the inputWidth, that’s why tou are getting this error, it tells you that the result of the expression int.Parse(input) which is an int cannot be converted to string which is the type of inputWidth.

Declare an int field, for example private int foo; and assign the result to that:
foo = int.Parse(input);

Thank you! I should have noticed that…

1 Like

This sort of has another “code smell” to it… why is the inputWidth field decorated with [SerializeField] if you are then going to overwrite it at runtime?

Yes, there are legitimate reasons to do this, but if you’re expecting that newly-inputted value to persist after running and stopping, it will not do that unless this field is within a ScriptableObject instance.

1 Like