An odd Object reference error

Hi folks,

For two days I’ve been pulling my hair out with this one. The error I’m seeing is:

NullReferenceException: Object reference not set to an instance of an object
InvaderControl+SetUpInvaders$25+$.MoveNext ()

referring to the line:

invaderClone[invaderNum].parent = invaderParent;

The code (based on the superbly commented Unity Invaders code) that’s causing this is:

var invaders : GameObject[];
var invaderColors : Color[];
var invaderMaterials : Material[];
private var sharedInvaderMaterials : Material[];

...

private var invaderClone : Transform[];
private var invaderParent : Transform;

...

	invaderClone = new Transform[columns * rows];	
	invaderParent.position = Vector3(0.0, 1000.0, zDistance);
	var rowCounter = 0;
	var invaderNum = 0;
	for (y = 0; y < rows; y++) {
		var invaderType = rowCounter++/2;
		for (x = 0; x < columns; x++) {
			invaderClone[invaderNum] =
				Instantiate(invaders[invaderType], Vector3((x*5.0)+3.0, -5.0+(y*2.0+startHeight)*3.0, zDistance), Quaternion.identity) as Transform;
			invaderClone[invaderNum].parent = invaderParent;
			invaderClone[invaderNum].gameObject.renderer.sharedMaterial = sharedInvaderMaterials[invaderType];
			invaderClone[invaderNum].gameObject.name = invaderType.ToString();	
			invaderNum++;
			
		}
	}

Thanks so much in advance! I’m lost, even after doing a huge number of related searches here.

Just before the offending line (ie, after the Instantiate call) put some code like:-

if (invaderClone[invaderNum] == null) {
    print("Null invader: " + invaderNum);
}

It’s most likely that one of the invaders isn’t getting instantiated properly, maybe due to a missing item in the invaders array.

Brilliant! Thanks so much for the debug tip. Turns out it’s throwing an exception with invader 0. At least I have something to work with now!

Thanks again,

John