Cannot modify the return value of 'Foo' because it is not a variable

You cannot modify members of value types directly via a property.


Do not directly modify a value type returned by a property or method. Instead choose one:


🔴 Incorrect#

Directly modifying a value type returned by a property.

transform.position.x = 1;

🟢 Correct#

Copying to a temporary variable that is then modified and set back to the original.

Vector3 p = transform.position;
p.x = 1;
transform.position = p;

🟢 Correct#

Constructing an entirely new value and assigning it as a whole.

Vector3 p = transform.position;
transform.position = new Vector3(1, p.y, p.z);

This same logic can be applied to any context where this error appears.


Direct modification to value types#

If the type is a value type (Vector3 for example) the entire value is copied when used by method, property, or assignment.
As the value is a copy, the original would not be modified when the copy is changed, which makes this code useless and a compiler error.

Direct modification to reference types#

If the type is a reference type (Transform for example) the reference (a pointer) is copied, and not the value itself.
As the value referenced is not a copy, making direct modifications to it makes sense.

I would like to learn more about value and reference types.