FormatException: Input string was not in the correct format System.Int32.Parse

Both of the following are returning error, what am I doing wrong?

var index = parseInt(“foo”);
var index = System.Int32.Parse(“foo”);

error:

FormatException: Input string was not in the correct format
System.Int32.Parse (System.String s)

1 Like

foo is no number so parse int will always fail
use int.TryParse to find out if it is a number at all before you try to use it as such

1 Like

Ok, thanks for the help.

Why did you think “foo” would not fail?

because the tutorial at http://active.tutsplus.com/tutorials/unity/getting-started-with-unity-colliders-unityscript/

has the following function where pickupCollected.name is string

ffunction Collected(pickupCollected:GameObject)
{
// retrieve name of the collected pickup and cast to int
var index:int = parseInt(pickupCollected.name);

// pickup has been destroyed so make the spawn index available again
spawnIndexAvailableList[index] = true;

// destroy the pickup
Destroy(pickupCollected);

// spawn a new pickup
SpawnPickup();
}

What is the proper syntax for tryParse I am getting compile errors:

var index : int = int.TryParse( “foo”);

where I would expect to return 0 since the parse will fail, correct? or am I missing something?

yeah but that tutorial is for objects named appropriately. you would name the object 0, 1 etc

and no, such errors will not result in a return of 0, it will throw an exception and the code flow will stop executing at exactly that point if not handled

From what I can tell the property pickupCollected.name needs to be defined as a number like “1”, “2”, “3”, etc… But the tutorial does not specify it that way. Appears to be a mistake in the tutorial. Thanks all for the help.

-GmG-

Looks like I came to the same conclusion :slight_smile: Thanks again!