NullReferenceException: Object reference not set to an instance of an object

I’m sure this is a simple fix for many of you. Thank you for any advice you can offer. I’m trying to respawn my enemy to a random set of coords. I’ve defined the coords in an array and cant get it to work.

I’ve gotten the enemy to respawn before by just using a random.range of integers, but when using the method below to generate specific coords I get the nullreferenceexception as soon as I shoot the enemy. The enemy also does not respawn.

The line that pulls the exception is “newX = coords[Random.Range(0, coords.Length-1)][0];”. I imagine it would do the same for the next line as well.

function OnTriggerEnter(otherObject: Collider){

	if(otherObject.gameObject.tag =="enemy"){
		playerscript.playerScore += 100;
		
		var newY : int;
		var newX : int;
		
		var coords = new Array(new Array(-8,8), new Array(0,8), new Array(8,8), new Array(8,0), new Array(8,-8), new Array(0,-8), new Array(-8,-8), new Array(-8,0));
		
		newX = coords[Random.Range(0, coords.Length-1)][0];
		newY = coords[Random.Range(0, coords.Length-1)][1];
		
	
		otherObject.gameObject.transform.position.x = newX;
		otherObject.gameObject.transform.position.y = newY;
		
		Destroy(gameObject); 
	}

OK, I have NO idea why you are trying to use all these arrays, just to come up with two random ints! just use Random.Range, forget all that other stuff:

function OnTriggerEnter(otherObject: Collider){

    if(otherObject.gameObject.tag =="enemy"){
       playerscript.playerScore += 100;

       var newY : int = Random.Range (-8,8);
       var newX : int = Random.Range (-8,8);

       otherObject.transform.position = Vector3(newX,newY,0);

       Destroy(gameObject); 
    }

EDIT:

the main point is this is not a very efficient way to do this… at the very most, one array (8,0,-8), would be all you would need, assuming you only want these values:

       var coords = new Array(-8,0,8);
       var newY : int = coords[Random.Range(0,3)];
       var newX : int = coords[Random.Range(0,3)];
       otherObject.transform.position = Vector3(newX,newY,0);

I also fixed the last line… Collider inherits transform directly, (but not gameObject either way)

Other than what Seth Bergman said, the solution to your Null Reference Exception is most likely because you’re getting the Length of a multidimensional array, when in fact you need to use GetLength(), where GetLength(0) is the row length, and GetLength(1) is the column length.

And from judging from what you’re ‘planning’ to do, Seth’s solution is not what you’re needing anyway, cause that would return any number between -8,7 ( because Random.Range is max exclusive ), whereas it looks like you’re trying to retrieve is -8, 0, or 8 as the integers and nothing else.