Array of transforms

Found little asking my old friend Googol so I am asking here : how do I create an array of targets (in my case transforms)?

I have this group of objects - defined in a public variable. But along the way, as I progress trough levels I want to activate more groups of objects (or targets); Or change them - activate or deactivate depending on level. So what I use now is :

var _targets:Transform;

And in the editor I assign it nicely. But I want more than one. Please link to some good docs:)

Did you mean var _targets:Transform[];? Are you wanting to add transforms to an array while you are playing? If so, then you'll have to convert _targets to a js array first, so then transforms can be added or removed, then converted back into a builtin array when you want to use the transforms in your script. See the examples on this page http://unity3d.com/support/documentation/ScriptReference/Array.html

The length of an array always returns last index + 1. Remember the array's index starts at 0. So an array holding [1,2,3] has a length of 3, but the last index is 2.

Sorry, so if I have two targets in my array, i use [1,2] or [0,1]? either gives me errors. Or putting it different, how do I add changes to all targets in my array?

1 Answer

1

UnityScript offers two different types of arrays:

  • Dynamic arrays, with the Array class (you can resize these at will)
  • Static arrays, with traditional “built-in” arrays (these have a fixed length)

The official script reference actually has a pretty good page explaining the two, including some examples.

Creating a built-in array is simple:

var _targets : Transform[]; //note the brackets

Creating a dynamic array is also simple:

var _targets = new Array(); //note the parens

From there, you can populate the array from the inspector and reference the elements of the array in your code.

If you’re going to be resizing the array from code on a regular basis, you might want to use Array. If not, you may want to use a built-in array. It’s really up to you.

I'll add that Array() are UnityScript only. I'd avoid them as the object they holds aren't typed, which makes it less performant. To have a resizable array-like variable, take a look at the System.Collections.Generic.List<T> class.

I would look [here][1] instead of the docs ... much better info covering all types of arrays ... also, as @BY0LOG1C said, you should most generally avoid Javascript Arrays. They are horrible for performance. Go with Generic Lists instead. :) [1]: http://unifycommunity.com/wiki/index.php?