Why didn't your Vector3 change?

Structs are copied. Here's what that means.

Why didn't your Vector3 change?

The problem

It won't even compile.

List<Vector3> path = GetPath(); path[0].y = 5f;// error CS1612: Cannot modify the return value// because it is not a variable

Vector3 is a struct. The list hands you a copy, and editing a temporary copy would do nothing.

Why it happens

Classes share. Structs copy.

Assigning a class gives you the same object. Assigning a struct gives you a new copy.

class
both names point to one object
struct
each name has its own copy

The fix

Copy out, change, put back.

var p = path[0];p.y = 5f;path[0] = p;

Take the copy, change it, and write it back into the list.

The sneaky version

It compiles, and does nothing.

var target = enemy.WorldPosition;target.z += 100f;// enemy hasn't moved! enemy.WorldPosition = target;

Changing a copy compiles fine. Nothing moves until you assign it back.

The rule

Changed a struct? Assign it back.

In a list
copy, edit, write back
A position
assign it back
Vector3, Rotation
structs