- Home /
Pushing GameObject into JS Array returns NullReferenceException
Hey there!
I'm trying to obtain a gameObject inside one array of a class, into a JS Array, so that later I can put it inside a builtin GameObject[] array. However when I try to do that, the Editor returns a NullReferenceException. I can assure you that the variable that's trying to be accessed isn't empty.
Here's the class + array in the script shipWeapons.js:
class WeaponSlot {
var isEnabled : boolean = false; //checks if the weapon is enabled
var weapon_go : GameObject; //weapon GameObject. It contains the projectile
var phaser_point : GameObject; //if the weapon is a beam weapon, it fires from this game object
var torpedo_point : GameObject; //if the weapon is a torpedo weapon, it fires from this game object
var pulse_point : GameObject; //if the weapon is a pulse weapon, it fires from this game object
var nextShot : float = 0.0f; //contains the time reference for when the weapon is able to fire again
var isAngle : boolean = false; //checks if the target is inside the firing arch
var isRange : boolean = false; //checks if the target is in range
var isFiring : boolean = false; //checks if the weapon is firing
var lastReload : float; //total time it took for the last reload
}
var weapon : WeaponSlot[];
And here's the attempt to build such array:
//and now the inventory part
//first get the weapon game objects of each weaponslot
var Arr : Array;
for(var x : int = 0; x < shipWea.weapon.Length; x++)
{
Arr.Push(shipWea.weapon[x].weapon_go);
}
var newWeapons : GameObject[] = Arr.ToBuiltin(GameObject) as GameObject[];
//now place it
playerShip.shipInv.weapons = newWeapons;
So, does anyone have an idea why this isn't working, and returning a NullReferenceException on Arr.Push()?
Thanks in advance. João Borrego
Answer by robertbu · Aug 31, 2013 at 06:01 PM
You declare and array variable, but you don't initialize it:
var Arr : Array = new Array();
But I highly recommend you not use the Array class. Use the .NET collections classes such as List or Stack.
http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F