Why does this tell me there is no instance of my object?

Hi, I currently have this function in my code:

function checkForClosest() : GameObject
	var foundShips = new GameObject[100];
	var closestShip : GameObject;
	for(var i : int = 0; i<=numShips;i++)
		if((newShips<em>.transform.position.x<= playerShip.transform.position.x + 50 && newShips<em>.transform.position.x >= playerShip.transform.position.x - 50)&&(newShips<em>.transform.position.y<= playerShip.transform.position.y + 50 && newShips<em>.transform.position.y >= playerShip.transform.position.y - 50)&&(newShips_.transform.position.x<= playerShip.transform.position.z + 50 && newShips*.transform.position.z >= playerShip.transform.position.z - 50))*_</em></em></em></em>

* {*
foundShips = newShips*;*
* }*
* }*
* closestShip = foundShips[0];*
* var dist = Vector3.Distance(playerShip.transform.position,closestShip.transform.position);*
* for(i = 0; i<=foundShips.length;i++)*
* {*
_ if(foundShips != null)
* {
var tempDist = Vector3.Distance(playerShip.transform.position,foundShips.transform.position);
if(tempDist < dist)
closestShip = foundShips;

The problem is that when I run it (after a button is pressed) it gives me the error "NullReferenceException: Object reference not set to an instance of an object
mainGUI.checkForClosest () (at Assets/mainGUI.js:261)"
Does anyone know where I went wrong?

Without knowing which line the error is on in your posted listing I would guess one of the two following things is true:

  • One or more entries in newShips is null - this seems quite possible to me, if one had been destroyed it would be null or if the number of ships was incorrect, which looks like it should be a “strange” number as your loop condition is <= normally that’s < with arrays.

    So either check for null, change your loop condition if that’s the problem and/or put in a null check like you have in foundShips.

  • Your playerShip is set to null, either because it hasn’t been initialized or because it has been destroyed.

In addition you’d be better off measuring distance for comparison using the squared magnitude as it is significantly faster:

  var tempDisp = (playerShip.transform.position - foundShips*.transform.position).sqrMagnitude;*

You would also get a performance bonus by making found ships an array of Transforms, caching the transform and the position in the first loop rather than continually deferencing it and adding the .transform to the found ships array. Given these arrays could be large you’d potentially get a big boost from this.