Can't modify List<Vector2> variables

Hi,

I seem to run into this problem all the time with Lists. I have the following:

List<Vector2> heartPos;
heartPos = new List<Vector2>();
heartPos.Add(new Vector2(Screen.width / 1.6f, Screen.height / 6));
heartPos.Add(new Vector2(Screen.width / 1.8f, Screen.height / 3));
heartPos.Add(new Vector2(Screen.width / 1.3f, Screen.height / 8));

for (int i = 0; i < heartPos.Count; i++)
            {
                float x = Random.Range(0, 2);
                float y = Random.Range(0, 1.5f);
                heartPos[i].x -= x;
                heartPos[i].y -= y;
            }

Compiler gives me the following errors:

error CS1612: Cannot modify the return value of ‘System.Collections.Generic.List<UnityEngine.Vector2>.this[int]’ because it is not a variable
error CS1612: Cannot modify the return value of ‘System.Collections.Generic.List<UnityEngine.Vector2>.this[int]’ because it is not a variable

How are they not variables? They are the x and y member variables of the Vector2.

I can read from these variables fine, but I cannot assign anything to them since initialisation. The following works:

float x = heartPos[0].x;

The following doesn’t work:

heartPos[0].x = 1;

As a test I did the following:

List<Vector2> test;
test.Add(new Vector2(1, 1));
test[0].x = 2;

This also failed with the same error. Am I initialising it incorrectly?

Vector2 is no class, its a struct.
Structs are passed around by value, not by struct so if you add them to something or get them as return, they are copies of the original data, they are not a reference to the object to change the original one that was returned.

Due to this the return you get from the list is read only, you can not update the struct on the list, you can only remove and readd it

I see you’re using Unity 2.6…Unity 3 has a better error message:

“error CS1612: Cannot modify a value type return value of `System.Collections.Generic.List<UnityEngine.Vector2>.this[int]'. Consider storing the value in a temporary variable”

So you’d do what the error says:

                var temp = heartPos[i];
                temp.x -= x;
                temp.y -= y;
                heartPos[i] = temp;

Note that this only applies to C#; JS does this for you.

–Eric

I’m actually using Unity 3. Version info:

Version 3.1.0f3 (54715)

Strange, because that error is only worded like that in Unity 2.6 as far as I know; starting with Unity 3.0 it suggests using a temporary variable.

–Eric