- Home /
Adding Arbitrary Properties to GameObjects
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.
Answer by DaveA · Jan 19, 2011 at 03:57 PM
Something like this pseudocode:
var thing : thingProperties; .....
Awake() .... thing = newThing.GetComponent("thingProperties"); thing.favoriteQuote = line.Sub.....
Your answer
Follow this Question
Related Questions
GetComponent vs AddComponent 3 Answers
Monobehaviour shared properties across single gameobject 2 Answers
How to get a component from an object and add it to another? (Copy components at runtime) 12 Answers
AddComponent for RawImage not functioning as expected 0 Answers
How to get a variable value from another script(C#)? 1 Answer