- Home /
Array problem
I get null reference errors when getting or setting any variable in this array. I've tried both methods of setting the array size initially (as it is now).. and reconstructing the area with the commented line in function Awake() that you see below. What am I doing wrong?
Also if anyone knows a more elegant way of looping through all the objects than what I'm doing now (a simple counter... ) I would be very grateful. I suppose I could use a generic for loop..
class ObjectData
{
var x : float;
var y : float;
var z : float;
var name : String;
}
class MapData
{
var _iLevel : ObjectData[];
function MapData() { }
}
private var myData : MapData;
function Awake () {
myData=new MapData();
var gameObjects : GameObject[] = FindObjectsOfType(GameObject) as GameObject[];
myData._iLevel = new ObjectData[gameObjects.Length];
for (var stats : GameObject in gameObjects) {
myData._iLevel[count].x = stats.transform.position.x;
myData._iLevel[count].y = stats.transform.position.y;
myData._iLevel[count].z = stats.transform.position.z;
myData._iLevel[count].name = stats.name;
count++;
}
}
Could you show us the 'UserData' object? You haven't posted that part of the script! In any case, it seems that there's no real relation between the number of elements in 'gameObjects' and the number of elements in 'myData._iLevel'. Why have you commented out the line just before the for-loop begins? It seems that that line is what's keeping the two values the same!
Fixed the variable type. It should be a $$anonymous$$apData type. Regarding the commented out line, I didn't think it needed to be there because the array was initialized with a static size in the class definition. However, now I've changed it back to how I want it to work. Define the array with no size, then recreate it using the number of GameObjects that I find. Still no go with this.
Well, I'm afraid I can't see any more problems here! Try putting Debug.Logs in everywhere, so that you can have some idea of exactly what is the null reference, and where the problems start occurring.
Answer by Michael Schenck · Jan 08, 2012 at 04:16 AM
You need to create the ObjectData instances - inside the for loop at top do myData.ILevel[count] = new ObjectData(); You just have an array of references to object data that is null. In C# I think you could make this a struct and you would be ok, but it is a class here, so you need to allocate it.
Your answer
Follow this Question
Related Questions
Activate/Deactivate Script from another Object. 3 Answers
Problem with moving objects in array? 2 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Quest Script Help 2 Answers