I’m trying to make an array in javascript. Usually this is a simple affair but I’m trying to dev for android (Ouya specifically) so I have to use “#pragma strict”. Unfortunately this seems to turn arrays into gameobjects no matter what I do!
If I call a normal array like so:
var spectrum = new Array();
Then Unity thinks it’s a gameobject type later on in my script. After some searching around, I discovered why Unity does this, but my attempts to resolve this issue don’t seem to work.
If I try to instantiate a native .NET array like so:
var spectrum : float[];
Unity returns the error message: “Object reference not set to an instance of an object” and points to where I used my array again. This message doesn’t pop-up until I run the game.
If I try to add in the length of the array (I think that’s how it works?):
var spectrum = float[64];
Then Unity says there’s no semi-colon. I think this is just a syntax error but there’s an example somewhere in the docs that recalls an array like this.
I’m pulling my hair out right now! I’ve tried all sorts of other weird combinations but Unity absolutely REFUSES to recognize my array as an array! Please help me T_T
var spectrum = new Array();
It is not gameObject type, it is Object
type. Whenever you need a specific function associated to a class, you need to cast the element in the array to use it.
var list = new Array();
list.Add( transform );
( (Transform) list *).Translate( ... );*
Reference: [http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?#Javascript_Arrays][1]
----------
var spectrum : float[];
This line of code has no problem, it is usually used to assign values in the inspector. “Object reference not set to an instance of an object” occurs when you run the game is because you neither assign any value to it in the inspector, nor initiate it in your Start()
.
How to work with this
1. Assign the values in the inspector
When you assign at least one values to the spectrum in the inspector, an array will be initiated to store the value
2. Initiate the array in Awake or Start
void Awake(){
spectrum = new float[32];
}
----------
var spectrum = float[64];
Plain typo error, the correct syntax should be:
- var spectrum = new float[64];
- var spectrum : float[] = new float[64];
[1]: http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?#Javascript_Arrays