- Home /
Converting Array Object to int (or finding an alternative)
Using Javascript and developing for Android.
I'm using arrays to create a resizable list of coordinates that will describe a path that the player will draw on a 6x6 grid. While I could technically rewrite the code to use static arrays, I would like to see if I can get resizable arrays working.
Here's the code:
var pathX = new Array();
var pathY = new Array();
function Start () {
pathX.Add(9);
pathY.Add(9);
//I cut a bunch of stuff out here that's irrelevant
}
function InPath (xx, yy) {
for (var i = 0; i < pathX.length; i++) {
if (pathX[i] == xx && pathY[i] == yy) {
return true;
}
}
}
function NearPath (xx : int, yy : int) {
if (pathX[pathX.length-1] == xx) {
if (Mathf.Abs(pathY[pathY.length-1] - yy) <= 1) {
return true;
}
} else if (pathY[pathX.length-1] == yy) {
if (Mathf.Abs(pathX[pathX.length-1] - xx) <= 1) {
return true;
}
} else {return false;}
}
It returns this error:
Assets/LevelControl.js(68,53): BCE0051: Operator '-' cannot be used with a left hand side of type 'Object' and a right hand side of type 'int'.
Because the array class stores everything as object types, it can't do the subtraction. Is there a way to make this work with arrays, or should I just convert over to a static array?
Answer by hoy_smallfry · May 22, 2013 at 09:11 PM
There's two ways this can be handled.
1) use System.Convert.ToInt32(System.Object obj)
before you use the subtraction operator:
var x : System.Object = 100;
var y = System.Convert.ToInt32(x) ;
Debug.Log("Type: " + x.GetType()); // should now be an System.Int32 aka int
Debug.Log("Value: " + x);
var z = y - 50;
2) Use List.< int >
instead of Array, which will avoid conversion altogether.
// goes up at the top of the script file
import System.Collections.Generic;
//...
var list : List.<int> = new List.<int>();
list.Add(100);
Debug.Log("Type: " + list[0].GetType()); // should be an System.Int32 aka int
Debug.Log("Value: " + list[0]);
var z = list[0] - 50;
Thanks, lists worked! Is there any documentation I can find on lists?
Your answer
Follow this Question
Related Questions
Is there a decent tutorial for a local high score table (android)? 1 Answer
Error when debuging array elements name 1 Answer
Building on android. 1 Answer
Sorting arrays? 1 Answer
How to delete new'd arrays? 2 Answers