- Home /
Don't see the cause of this NullReferenceException...
When I try to assign the instantiated object to batReferences[0].enemy
in the array, it throws: NullReferenceException: Object reference not set to an instance of an object. Can anyone tell me why? It's nothing to do with the instantiated object not existing, I can try assigning any gameObject to the array and it throws the same error…
var batPrefab : GameObject;
private var batReferences : EnemyClass[];
class EnemyClass
{
var enemy : GameObject;
var material : Material;
var batScript : BatScript;
var activated : boolean;
}
function Start ()
{
// Instantiate enemy
batReferences = new EnemyClass[3];
var newEnemy = Instantiate( batPrefab );
batReferences[0].enemy = newEnemy; // NullReferenceException
}
Answer by robertbu · May 16, 2013 at 04:52 AM
You've created an empty array, but you've not created and initialized all the EnemyClass instances for the elements in the array. All you have is an array of null references. You need to add some array initialization:
for (var i = 0; i < batReferences.Length; i++)
batReferences[i] = new EnemyClass();
So saying var array = new EnemyClass[1]; is not the same as saying array[0] = new EnemyClass();? Even though var array = new GameObject[1]; does work straight out of the box? =S
I guess it's just different when using Classes. Initializing each array item individually seems to do the trick though!
objects are initialzed to there default value.
the default value of a reference type is null.
basically EnemyClass is a GameObject. thats a reference object.
Pretty much only the built in types (int, char, bool) have a default value that isn't null. Thats because objects of that type are not allowed to be equal to null. Therefore they initialize to non null.
Objects of a reference type (classes ) initialize to null. That is done by the compiler in accordance with the language specifications.