- Home /
Reading and Storing External Data into Memory (From Text)
I'm using JavaScript, so I think this will make a big difference compared to other languages.
//count the number of items we need to load in
4
//[ITEMID] : [SCALEX] , [SCALEY] : [TEXTURENAME] : [STEPCOUNT] : [STEPS] , ... , [STEPSN]
0 : 1, 1 : foo : 3 : 0, 1, 2
1 : 1, 1 : bar : 3 : 2, 1, 0
2 : 2, 2 : pud : 5 : 1, 2, 3, 4, 5
3 : 3, 3 : lye : 8 : 1, 2, 3, 4, 5, 6, 7, 8
So, this is a new area of Unity that I haven't experienced yet. I know how to load and read data into fixed-size arrays in Unity. This one I'm not so sure about, because the data-types change (and that a field can have an N amount of values). However, prior programming experience tells me that this ends up turning into (pseudocode):
class CustomClass
ID as integer
Scale as Vector2
Tex as string
Count as integer
Steps[] as integer
end class
classArray as List<CustomClass>
Thankfully, this data is fixed - it will never get modified while in memory and won't need to be saved on exit. How does one go about defining a class array and populating it in JavaScript? Any pointers or tips?
Answer by TowerOfBricks · Jul 28, 2012 at 12:35 PM
My UnityScript is a bit rusty, but I know you can use the class Array (yes, the class named Array). http://docs.unity3d.com/Documentation/ScriptReference/Array.html
So if you define a class like that. You could do something like this: (pseudocodish, almost valid UnityScript). The read... functions could be any text reader class you use to parse the information.
var arr = new Array ();
var itemcount = readInteger ();
for (var i=0;i<itemcount;i++) {
var obj = new CustomClass ();
obj.ID = readInteger ();
obj.Scale = new Vector2 (readFloat(),readFloat(),readFloat ());
obj.Tex = readString ();
obj.Count = readInteger ();
obj.Steps = new int[obj.Count]; //Count was to be used for this, right?
for (var j=0;j<obj.Steps.length;j++) obj.Steps[j] = readInteger ();
arr.Add (obj);
}
It would be preferable to use
List.<CustomClass>
over Array - type safety, same access methods.
Yes probably better. As I said, my UnityScript is a bit rusty, so I wasn't sure how to use it in UnityScript. Only in C#. So I went for the safe approach.
It's a wacky format, I can't quite get used to typing "dot" "less than" - screams wrong to me :)
Wait... It is actually valid UnityScript to write List.<....> !? Though that dot was a typing error of yours. That just looks ugly.