0

I'm trying to get user's height from the input and do if-else statement, then display the size of clothes they should get according to their height. I have no idea how to convert string to a number.

Here's my code:

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

public class NewBehaviourScript : MonoBehaviour
{
    public string number;
    public GameObject inputField;
    public GameObject textDisplay;

    public void ShowSize() {
        number = inputField.GetComponent<Text>().text;

        if (number <= 167) {
            textDisplay.GetComponent<Text>().text = "You are suitable to get S size.";
        }
        else if (number >= 168 && number <= 177) {
            textDisplay.GetComponent<Text>().text = "You are suitable to get M size.";
        }
        else if (number >= 178 && number <= 184) {
            textDisplay.GetComponent<Text>().text = "You are suitable to get L size.";
        }
        else if (number >= 185) {
            textDisplay.GetComponent<Text>().text = "You are suitable to get XL size.";
        }
        else {
            textDisplay.GetComponent<Text>().text = "Please enter a correct height!";
        }
    }
}

Any help would be appreciated, thank you!

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
Wei Kang
  • 3
  • 2
  • 3
    Does this answer your question? [How can I convert String to Int?](https://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) – fuzzybear Aug 09 '20 at 16:57

2 Answers2

0

Try int.Parse(tempString); mate, it should work perfectly for your case, it should be like this i think:

if (int.parse(number) <= 167 ) {
            textDisplay.GetComponent<Text>().text = "You are suitable to get S size.";
        }
Kanna
  • 163
  • 1
  • 12
0

int.parse will work, however, if you ever have a string with anything BUT numeric characters, it can fail and leave you hanging and guessing... the "TRYPARSE" method take an OUT parameter, and if it was successfully parsed will put the value in that field for you to work with.

int number;
if(Int32.TryParse( inputField.GetComponent<Text>().text, out number))
{
  // you have a valid number... Similar if you tried to do a 
  // decimal or double, or other numeric type... 
}
DRapp
  • 47,638
  • 12
  • 72
  • 142