- Home /
Conceptual Question on Creating Arrays at Runtime
Hello everyone, I've been needing to do some work with arrays that store data types like Transforms on gameobjects, scripts on gameobjects, etc at runtime. My current understanding is that if I wanted, say, an array of Transforms, I would first need to create an array of gameobjects then pull the transforms (or I guess Vector3) data from that first array, since you cannot use methods like getcomponent() if you are doing say find.objectswithtag, since casting or using "as" doesn't seem to work.
Is my understanding correct? If not, what is the best way to go about creating these types of arrays at runtime?
Answer by knowpixels · Aug 02, 2014 at 02:03 AM
There are 2 types of Arrays in Unity Script.
The "Built In" arrays, such as Vector3[] and GameObject[]. These builtin arrays run very fast and you can create one at runtime with code using a runtime declaration such as
var ga:GameObject[]; ga = GameObject.FindGameObjectsWithTag("Collectables");
That would declare and then populate a builtin array called ga with all the gameobjects tagged Collectables. Built in arrays are the ones you see in the inspector. The restriction is the array size or length cannot be altered at runtime.
The native javascript arrays which use the standard declaration syntax
var ga:Array = new Array(Vector3(0,0,0),Vector3(0,0,0));
Native JS arrays are no where near as fast but they are flexible so you can push (Add) and splice and all things nice :)
When it comes to deciding which one to use I would recommend using built in arrays for the sheer speed of them when you know you will not need to change the array size or length. However if your array will require total flexibility at runtime and you are willing to take a performance hit then go for a native JS array.
There are scenarios where you may need to create a native JS array at runtime and dynamically populate it with say Vector3 instances that are randomly generated and then take the dynamic values of your new native JS array and copy them into a new built in array. My use case was for creature AI patrol points random generation and regeneration logic.
To pass my random dynamic values in my native JS array into a unity built in array at runtime I used the ToBuiltin() function from documentation :
randomPatrolWayPoints = tempArray.ToBuiltin(Vector3) as Vector3[];
So 2 types of array, built in and native JS array. Built in is faster but inflexible and native arrays are slower but have all the flexibility that could be required.
Also when using built in arrays the For(a:GameObject in myGameObjectsArray){} is faster that the traditional for loop.
^_^
You realize you are answering a question from February?
Yarp ;) must be feeling helpful as I am 34 today.. Happy birthday to me, because all my arrays were builtin Vector3... heh heh :D