JS Code problems, string not parsing to int.

Hello, I’m working on a simple game where you guess a random number out of 1 - 100 and you only get 10 tries to guess it. Right now I’m attempting to add a GUI label, using js of course, and I am encountering a problem.

I have these two variables:

var guess:String;
var numberGen:int;

numberGen is the randomly generated number which is 1 - 100 and guess is the TextField:

guess = GUI.TextField(Rect(550,200,30,20), guess, 25);

Now here is where my problem is, even when parsing to an integer as you see here:

if (GUI.Button(Rect(535,230,60,40), "Accept")) {
	if (numberGen == parseInt(guess)) {
		if(guess < numberGen) {
			print("Test");
		}
		if(guess > numberGen) {
			print("Test2");
		}
	}
	guesses--;
}

I still encounter this problem :

(Assets/WordGame.js(42,42): BCE0051: Operator '<' cannot be used with a left hand side of type 'String' and a right hand side of type 'int'.)
and
(Assets/WordGame.js(45,42): BCE0051: Operator '>' cannot be used with a left hand side of type 'String' and a right hand side of type 'int'.)

I don’t get why it’s still counting it as string even though I have the (if(guess < numberGen)) under the parse int.

I am a bit of a newbie when it comes to video game programming, especially since I have never learned js until a couple of weeks ago. Any help would be greatly appreciated.

1 Answer

1

Unity doesn’t actually use an implementation of [ECMAScript][1] or

[2].  What you see in Unity is a JavaScript syntax like language which should just be renamed everywhere as unityscript. but even unity mixes and matches between the two.  Do no expect JavaScript functions to exist in unity unless the documentation states otherwise.

You need to use the correct equivalent for converting into a int, luckly there are methods for this, please look at the modified code below.

    var guessInt : int = int.Parse(guess);
    
    if (GUI.Button(Rect(535,230,60,40), "Accept")) {
        if (numberGen == guessInt) {
            if(guessInt < numberGen) {
                print("Test");
            }
            if(guessInt > numberGen) {
                print("Test2");
            }
        }
        guesses--;
    }

Also, do the conversion once and store the result. You would need to do it three times otherwise(or the possibility of three times).  Also as a note, your logic doesn't make sense.  If numberGen is EQUAL to the guess number as a int, you will never hit whether it's less than or greater than.... you already established it was equal to.

  [1]: http://en.wikipedia.org/wiki/ECMAScript
  [2]: http://en.wikipedia.org/wiki/ECMAScript