x


ArrayLists or Tags?

Generally speaking, is it quicker to get objects via their tags or from an array (ArrayList)?

Example:

var apples = GetComponent("FruitBasket").apples;
for (var a : GameObject in apples)
{
//eat apple or something
}

OR

for (var a in GameObject.FindGameObjectsWithTag("apple"))
{
//eat apple or somthing
}

thanks!

more ▼

asked Feb 14 '11 at 01:30 PM

rule62 gravatar image

rule62
79 15 18 24

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

1 answer: sort voted first

The difference in what you're doing should be unnoticeable. It would only start to matter if you were calling FindGameObjectsWithTag or GetComponent in a loop. Do whatever's easier.

However, this is slow:

GetComponent("FruitBasket").apples;

Do this instead:

GetComponent.<FruitBasket>().apples;

All that said, GetComponent is likely faster than FindGameObjectsWithTag, and GetComponent is easier to deal with, because it doesn't have to deal with a string. Strings, in this case, don't generate helpful errors at compile-time. The fastest possible thing would be to store a reference to the FruitBasket component, and not call GetComponent on it at runtime, but you're never going to notice this performance increase. Only store that reference if you're going to use it a lot.

Edit:

You can use the script's drop-down menu, in the Inspector, to call CacheReferences, or you could call the function from code, whenever you want. You can set up as many variables as you like, with the function, hence the name I gave it. Add to it if it would be helpful.

http://unity3d.com/support/documentation/ScriptReference/ContextMenu.html

var fruitBasket : FruitBasket;

@ ContextMenu ("Cache References")
function CacheReferences () {
    fruitBasket = GetComponent.<FruitBasket>();
}

function EatApplesOrSomething () {
    for (var apple in fruitBasket.apples) {
        //eat apple or something
    }
}
more ▼

answered Feb 14 '11 at 02:41 PM

Jessy gravatar image

Jessy
15.6k 72 95 196

Thanks Jessy! Can I ask what you'd suggest as far as storing a reference to the FruitBasket component? I'm not sure what for this "reference" would take. cheers!

Feb 14 '11 at 03:11 PM rule62

Sure. I've put an example of how to do that after the Edit. A "reference", in this case, is just a variable that links the FruitBasket object to a variable.

Feb 14 '11 at 03:28 PM Jessy

Ah ok. Awesome, thanks!

Feb 14 '11 at 03:31 PM rule62
(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:

x2076
x660
x321
x72

asked: Feb 14 '11 at 01:30 PM

Seen: 920 times

Last Updated: Feb 14 '11 at 01:37 PM