Let's say we are creating an array of GameObjects as we read a text file like so:
masterScript.js
import System;
import System.IO;
import System.Text.RegularExpressions;
var textAsset : TextAsset;
var things : ArrayList;
var thingsPrefab : GameObject;
function Awake() {
var things = new ArrayList();
if (textAsset == null) return;
reader = new StringReader(textAsset.text);
line = reader.ReadLine();
while (line != null)
{
var newThing = Instantiate(thingPrefab,Vector3.zero,Quaternion.identity);
things.Add(newThing.gameObject); //arraylist
line = reader.ReadLine();
// test for reading halt condition
}
}
Let's say we want to add some arbitrary properties to each of our GameObjects. Let's focus on non-graphical properties to keep things clear. We parse these properties as we read each line.
The way I'm currently doing it, is to add a "blank" script to "store" the properties for each object. So, I attach the blank script and assign the properties to variables.
thingProperties.js
var numBoats : int;
var petName : String;
var favoriteQuote : String;
function Awake () {
//not doing anything yet
}
So, inside our reading loop, we end up with this:
while(line != null)
{
var newThing = Instantiate(thingPrefab,Vector3.zero,Quaternion.identity);
things.Add(newThing,gameObject);
newThing.AddComponent("thingProperties");
newThing.GetComponent("thingProperties").petName = line.Substring(0,10);
newThing.GetComponent("thingProperties").numBoats = int.Parse(line.Substring(11,2);
newThing.GetComponent("thingProperties").favoriteQuote = line.Substring(25,80);
}
This is the strained effort of a javascript noob, but it looks wildly inefficient to me. Clearly the thingProperties script could be added to the thingPrefab. But all these "GetComponent"s look like they might be "slow". I'd like to optimize this code.
Any help would be much appreciated.