x


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 http://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.

more ▼

asked Jan 19 '11 at 02:51 PM

pickledzebra gravatar image

pickledzebra
286 31 35 44

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Something like this pseudocode:

var thing : thingProperties;
.....

Awake()
....
  thing = newThing.GetComponent("thingProperties");
  thing.favoriteQuote = line.Sub.....
more ▼

answered Jan 19 '11 at 03:57 PM

DaveA gravatar image

DaveA
26.5k 151 171 256

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2090
x406
x77
x76
x72

asked: Jan 19 '11 at 02:51 PM

Seen: 2013 times

Last Updated: Jan 19 '11 at 02:51 PM