I am working in java script, and creating an array. For some reason, unity is giving me an error “implicit downcast from object to int”
Here is a sample of the code causing the error:
internal var testarray : Array[] = new Array [3];
function Start () {
testarray[0] = [0,1,2,3];
testarray[1] = [4,5,6,7];
testfunction(testarray[0][2]);
}
function testfunction ( testvar : int)
{
}
I get this error a lot, and its usually because I forgot do define a variable. So I fix it. But this time, I have defined the variable, and yet its still giving the error. Does anyone know why?
Um, you can't do Array[3], Array does not have a set size, therefore it's just Array()
Well, Arrays are collections of objects. That’s just all they know how to do. If you want specific types you should use List (which also gives you type safety and lots of nice functions like Sort and greatly reduces the number of casts you have to do)
To get from an Array entry to a specific type, you have to cast. Either (type)array[index], or array[index] as type, depending on stuff. Base types like int and float and such need (int)array[index].
The () method can throw exceptions, while the as method can return null (in case you want to check ob as GameObject != null)
I can't seem to get the () method to work. I tried doing this: internal var testarray : Array[] = new Array[3]; function Start () { testarray[0] = [0,1,2,3]; testarray[1] = [4,5,6,7]; testfunction((int)testarray[0][2]); testfunction((int)testarray[2][1]); } function testfunction ( testvar : int) { } I tried a few other times by placing "(int)" in other places, but nothings worked. Does anyone know how to do this?
Casting is nasty. (int)testarray[2][1] converts testarray[2] to an int, then calls [1] on it, which explodes the everything. (int)(testarray[2][1]) will do it. Ben: It's a [] array of Arrays. ... ... @_@
Don’t use Array. Use built-in arrays, or generic Lists.
var testArray : int[,];
function Start () {
testArray = new int[4, 2];
testArray[0, 0] = 55;
}
Ok, I have heard Lists mentioned a lot, and I have no idea what they are. I tried to look them up, but learned that they involve C#. I am using JavaScript. I would use a built-in array, but for what im doing, they don't work for what im using my array for.
Lists don't have anything to do with C#, they're a .NET/Mono feature. A built-in array does do exactly what you're using your array for. I just demonstrated that with the code example above.
Um, you can't do
– Benproductions1Array[3],Arraydoes not have a set size, therefore it's justArray()