Home > Software engineering >  Set value on GameObject.transform.position[index] with C#
Set value on GameObject.transform.position[index] with C#

Time:03-24

I have a float array to store GameObject.position value, how can I give the value to the GameObject.position by using indexing?

var positions = new [0f,10f,12f];

for (int i = 0; i < 3; i  ){
GameObject.position[i] = positions[i]
}

CodePudding user response:

Transform.position is a property with a getter and a setter.

You can not directly assign individual components - since it would basically only apply it to the returned Vector3 from the getter but not invoke the setter.

You always need to get and set an entire Vector3 value to the property like

var vector = Vector3.zero;
for (int i = 0; i < 3; i  )
{
    vector[i] = positions[i]
}
GameObject.transform.position = vector;

CodePudding user response:

You need to use Transform. Transform has position, rotation and scale. To set position you can set only full value, so:

GameObject.transform.position = new Vector3(positions[0], positions[1], positions[2]);
  • Related