- Home /
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
found this: http://answers.unity3d.com/questions/46468/how-do-i-create-an-array-for-multiple-targets.html
and it works well, I suppose I can activate/deactivate stuff on the go; problem is I need to figure out how to specify more than one group in the array (or the entire length):
Now I am using var _targets:Transform[]; .....
if ( _targetsHit == _targets[1].childCount && _resetLevel == false )
but if I use _targets[_targets.Length] I get an array out if index error. Also, wouldn't this give more errors if I have a group in the array inactive at one point?
I'll check the link in the answer thanks!
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?
Answer by rutter · Apr 10, 2012 at 10:28 PM
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)
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 class.