I’m trying to assign all the positions of a number of gameObjects to an array This is what I have done:
var limbs : GameObject[];
var limbsPos : Vector3[];
var limbRot : Vector3[];
private var length : int = 0;
function Start (){
limbs = GameObject.FindGameObjectsWithTag ("Limb");
for(var limb in limbs){
limbsPos = new Vector3[limbs.length];
print (limb.transform.position);
//The next line works
//limbsPos[3] = limb.transform.position;
//This one doesn't
limbsPos[length] = limb.transform.position;
length++;
}
print (limbsPos[3]);
}
However, when assigning to limbsPos, assigning a specific number works ( [3] ) but assigning by a variable doesn’t. What am I doing wrong?
You recreate the limbsPos array each iteration. So only the last element will be preserved.
Second if two or more arrays are involved it’s usually more readable to use a “normal” forloop and not a for each loop.
Something like this:
var limbs : GameObject[];
var limbsPos : Vector3[];
var limbRot : Vector3[];
function Start ()
{
limbs = GameObject.FindGameObjectsWithTag ("Limb");
limbsPos = new Vector3[limbs.length];
limbRot = new Vector3[limbs.length];
for(var i = 0; i < limbs.Length; i++)
{
limbsPos _= limbs*.transform.position;*_
limbRot = limbs*.transform.eulerAngles;* } } Also are you sure you need euler angles? Usually it’s better to directly use [Quaternions][1]. Also do you need the position and rotation seperate? Usually it’s easier and more flexible to use a transform array. If the “limbs” are moving and you just want to store a snapshot, it’s ok _*[1]: http://unity3d.com/support/documentation/ScriptReference/Quaternion*_
For reference, here is the version I am now using:
var limbs : GameObject[];
var limbsPos : Vector3[];
var limbsRot : Vector3[];
function Start (){
limbs = GameObject.FindGameObjectsWithTag ("Limb");
limbsPos = new Vector3[limbs.length];
limbsRot = new Vector3[limbs.length];
for(var i = 0; i < limbs.Length; i++){
limbsPos _= limbs*.transform.position;*_