Search Unity

Vector2.Set() in a List of Vector2's problem

Discussion in 'Scripting' started by herpanda, Feb 26, 2014.

  1. herpanda

    herpanda

    Joined:
    Jan 1, 2014
    Posts:
    27
    Hey all,

    How does .Set() work? I have a single test Vector2 and it works as expected, and (1,1) is displayed in the debug.

    Code (csharp):
    1. //Works!
    2. Vector2 test = new Vector2(0,0);
    3. test.Set(1, 1);
    4. Debug.Log("test" + test);
    5. //(1,1) displayed
    6.  
    However, in my project I have a List of Vector2's in a class's attributes to make my code cleaner. In the update function, I iterate through the list and modify each using .Set(), but the Vector2's aren't being modified and still display (0,0) as shown below:

    Code (csharp):
    1. //doesn't work :(
    2. List<Vector2> testList = new List<Vector2>();
    3. for(int j = 0; j < 5; j++){
    4.      testList.Add(new Vector2(0,0));
    5.      testList[j].Set(1, 1);
    6.      Debug.Log(testList[j]); //(0,0) still displayed
    7. }
    I can set the vectors from the list using "testList[j] = new Vector2(1,1);" but this code is being run in every fixed update for every entity, and I don't want to call new that many times when I can just use my original Vector2. Any help on the matter is appreciated, thanks.
     
  2. popeye1

    popeye1

    Joined:
    Dec 19, 2014
    Posts:
    28
    Having same problem when trying to set the velocity vector.
    obj.rigidbody2D.velocity.Set(this.maxSpeed , obj.rigidbody2D.velocity.y);

    But I don't have your problem so I guess the velocity isn't possible to change with the Set or its a bug.

    Vector2 test = Vector2.zero;
    Debug.Log (test);
    test.Set (1, 1);
    Debug.Log (test);

    Works good for me.
     
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    It's not a bug. Vector2 is a struct so it's a value type. When you pick it out of a list you're getting a copy back, not the one in the list. In terms of velocity - it's actually a property. Value type properties return a copy.
     
  4. ZO5KmUG6R

    ZO5KmUG6R

    Joined:
    Jul 15, 2010
    Posts:
    490
    You'll have to do

    list[index] = new Vector2(x,y).
     
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Or treat it the same way you do properties
    Code (csharp):
    1.  
    2. Vector2 item = list[0];
    3. item.Set(1, 1);
    4. list[0] = item;
    5.  
     
    ZO5KmUG6R likes this.
  6. popeye1

    popeye1

    Joined:
    Dec 19, 2014
    Posts:
    28
    Ok, so in the velocity case this is the way to handle it
    if you don't want to use new?
    Vector2 tmp;
    tmp = rigidBody2D.velocity;
    tmp.Set(0,5f);
    rigidBody2D.velocity = tmp;
     
  7. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Aside from the fact that lines 1 and 2 could be combined - yes :)