Home > OS >  How to store GameObject.position in to the new array?
How to store GameObject.position in to the new array?

Time:03-02

I have a GameObject array, how can I store the GameObject.position into the new array by using a float[]?

I try to use the below code, but it's not working...

public float[] Storeposition;
public GameObject[] Go;

public save(){
   storeposition = new float[Go.count * 3]
   for(int i = 0; i < Go.count; i  ){ 
       for(int b = 0; b < (Go.count * 3); b  ){ 
       storeposition[b] = Go[i].transform.position.x;
       storeposition[b   1] = Go[i].transform.position.y;
       storeposition[b   2] = Go[i].transform.position.z;
       b = b   2
}
}
}

CodePudding user response:

Vector3 allows indexing to access the individual components of the vector

var myVector3 = new Vector3(4, 5, 6);

var xComponent = myVector3[0]; // 4
var yComponent = myVector3[1]; // 5
var zComponent = myVector3[2]; // 6

This helps us simplify the for loop by accessing each component directly using the current iterator.

var positions = new float[gameObjects.Length * 3];

for (int i = 0; i < gameObjects.Length; i  )
{
    for (int ii = 0; ii < 3; ii  )
    {
        positions[i * 3   ii] = gameObjects[i].transform.position[ii];
    }
}
  • Related