How to change x,y,z values in a Vector3 properly in c#?

Hi all,

I recently made the change from javascript to c# in all my unity scripts.

Now in Javascript, I can do this with a Vector3, no problems:

myVector.x = new_x;
myVector.y = new_y;
myVector.z = new_z;

However, this same code fails to compile in C#, with an error message about using a temporary variable to store the values. As a workaround, I’ve found that this way it works:

myVector = new Vector3(new_x,new_y,new_z);

This gets annoying when dealing with vectors with long names, like transform.position, or when I simply need to change one of three coordinates. Why is it that X,y and Z cannot be directly accessed and is there a simpler way to reassign just one of them? When dealing with transform.position, the position itself allows me to reassign a new Vector3, but not the individual values. Can someone please clarify this for me?

This happens because Vector3 is a struct and Transform.position is a getter method that retrieves the position member, but because its a struct it is passed by value and not by reference.

Basically, ever time you call Transform.position, a new Vector3 struct is allocated with the values of position, but it’s not in fact the same position object, so semantically it makes no sense to say “transform.position.x = 10.0f”, because what it really means is “change the value a random Vector3’s x property allocated somewhere on the heap to 10, and then discard it as it is not referenced anywhere”

You can either keep using your method, or alternatively store the result of transform.position, modify it, and then re-assign:

Vector3 temp = transform.position;
temp.x = 10.0f;
transform.position = temp;

[Edit]
Looks like we can edit posts again!
Just wanted to add that if you’re want to further read about this, you can check out http://msdn.microsoft.com/en-us/library/wydkhw2c.aspx, The second exmaple explains what happens with transform.position

The only way I found is:

Vector3 tmpPos = transform.position; // Store all Vector3
tmpPos.y = 1.3f; // example assign individual fox Y axe
transform.position = tmpPos; // Assign back all Vector3

Declare a static method somewhere in your solution:

public static Vector3 Change(this Vector3 org, object x = null, object y = null, object z = null) {
     return new Vector3( (x==null? org.x, (float)x), (y==null? org.y, (float)y), (z==null? org.z, (float)z) );
}

Call it by:

transform.position = transform.position.Change( y: 1.3f );