How to turn a TMPro text into an integer

I have a problem where, when try and convert a TMPro.text into an integer with the Parse function is says “FormatException: Input string was not in a correct format.”. I tried the same function with a string variable set to “10” and that worked completely fine, I also used the get getType function which said that the TMPro.text was a string. I have already searched a lot of forums but none of them seemed to have my answer. This is basically what my code looks like

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class Player : MonoBehaviour
{
public int speed;
public float jumpHieght;

public Vector2 movement;

public Rigidbody2D rb;
public SpriteRenderer sr;

public TextMeshProUGUI speedInput;
public string stringSpeed;

void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = 0;

if (movement.x == 1) {
sr.flipX = false;
}
if (movement.x == -1) {
sr.flipX = true;
}

if (Input.GetKeyDown(KeyCode.Space)) {
rb.AddForce(new Vector3(0, jumpHieght * 100, 0));
}
}

void FixedUpdate()
{
// Movement
rb.velocity = new Vector2(movement.x * (speed * 10) * Time.fixedDeltaTime, rb.velocity.y);
}

public void ReadFloatInput() {

stringSpeed = speedInput.text;
//stringSpeed = "50";
Debug.Log(stringSpeed);

speed = int.Parse(stringSpeed);
}

If anyone can figure out why it isn’t working this isn’t working that would be super helpful, thanks

Since this is user input you should prefer to use TryParse() since parsing may fail. That way you can restore the previous value or use a safe default value.

If TryParse fails (returns false) you can log the input text to see if that was not a correct number.
Also, if you need to parse float in the future, keep in mind that „1.234“ and „1,234“ can mean different values depending on locale. :wink:

@Fried_guy Also, and I’m not sure why this happens so often lately, please make sure to use code tags for the code, not icode which is used for inlined strings.

normal code
  with indentation
    preserved

Btw I wouldn’t recommend converting from string to integer EVER, but if you really have a strong case, I concur with CodeSmile’s reply.