Search Unity

why this code doesn't work ? c# ?

Discussion in 'Scripting' started by m-y, Oct 31, 2014.

  1. m-y

    m-y

    Joined:
    Sep 22, 2013
    Posts:
    472
    hi i want my cube when jump if i press (any key )
    transform.position.y = number ;
    that is my code


    Code (CSharp):
    1. else    if ( Swipe_value < 0 )
    2.                     {
    3.                         float y = transform.position.y ;
    4.  
    5.                         y = -14.1365f ;
    6. }
    7.  

    but this code doesnt work
    any reason ?
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  3. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Code (csharp):
    1. Vector3 updatedPosition = transform.position;
    2. updatedPosition.y = -14.1365f;
    3. transform.position = updatedPosition;
     
  4. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    So here you're dealing with the difference between VALUE types and REFERENCE types. Pretty much, the Vector3 and the y float you get are *copies* so changing them will not affect the transform.

    This is why we need to assign the entire Vector3 back to transform.position at once. Otherwise you are changing copies of values and not the actual values the transform is using.

    http://www.albahari.com/valuevsreftypes.aspx
     
    m-y likes this.