- Home /
Question by
Cyberpie_n_milk · Mar 15, 2013 at 05:40 PM ·
javascriptarrayerror messageaccess
Can't edit built-in array through script unless viewed in Inspector
class Data{
public var x : float;
public var y : float;
public var z : float;
public var name : String;
}
class DataClass{
var allObjects:Data[] = new Data[0];
function DataClass() { }
}
var objectData:DataClass;
function Start(){
var foundObjects = GameObject.FindObjectsOfType(Transform);
objectData.allObjects = new Data[foundObjects.Length];
yield WaitForSeconds(1);
for(var num:int;num<foundObjects.Length;num++){
objectData.allObjects[num].x = foundObjects[num].position.x; //Error here
objectData.allObjects[num].y = foundObjects[num].position.y;
objectData.allObjects[num].z = foundObjects[num].position.z;
objectData.allObjects[num].name = foundObjects[num].name;
}
}
When I run this and the objectData array isn't displayed in the Inspector, I get "NullReferenceException: Object reference not set to an instance of an object". This also happens if I remove the yield or make the array static or private.
If I select the gameobject with the script, so I can see the array in the Inspector, it works.
Comment
Best Answer
Answer by robertbu · Mar 15, 2013 at 06:32 PM
On line 18, you create an array of Data objects, but you don't initialize the entry of the array with Data objects. Insert something like this between lines 18 and 19.
for (var i = 0; i < objectData.allObjects.Length; i++)
objectData.allObjects[i] = new Data();