- Home /
Cant fix a null reference exception?
So I'm getting a null reference exception and I can't figure out how to fix it. Heres the code and line its on.
private var ship : GameObject;
private var planets : Array;
private var stuckDistance : float;
private var planet : GameObject;
function Start () {
ship = GameObject.Find("Ship");
planets = new Array();
planets.length = 4;
planets[0] = GameObject.Find("Planet_1");
planets[1] = GameObject.Find("Planet_2");
planets[2] = GameObject.Find("Planet_3");
planets[3] = GameObject.Find("Planet_4");
stuckDistance = 15.0f;
}
function Update () {
for (var p = 0; p < 4; p++)
{
if((Vector3.Distance (transform.position, planets[p].transform.position)) <= stuckDistance)
{
planet = planets[p];
}
}
transform.position = planet.transform.position;//line with null exception
refueling = true;
}
my working theory right now is maybe i have to declare the array differently? I'm looking at the scripting reference but I'm not seeing anything very helpful. anyone have any ideas?
Answer by robertbu · Dec 08, 2013 at 06:37 PM
If you had used '#pragma strict' at the top of the file, your code would generate an error which I believe points you in the right direction. First avoid the 'Array' class. If you need an array and you know it size (i.e. it does not have to grow), use a built-in array. If it needs to grow or change size, consider a .NET generic List. Here is a reference:
http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F
As for your specific bug here, delete lines 8 and 9 and declare your array on line 2 as:
private var planets : GameObject[] = new GameObject[4];
Note you if you still get a null reference exception, then it is likely that your GameObject.Find() is failing. Check for exact spelling and case.