Search Unity

Changing a single component of a Vector3

Discussion in 'Scripting' started by Rodentman87, Mar 27, 2015.

  1. Rodentman87

    Rodentman87

    Joined:
    Mar 27, 2015
    Posts:
    4
    I am working on a project where I need to change just the z component of a transform. What I currently have is:

    transform.position.z = x;

    but there is a compile error.

    EDIT: Solved

    I just made a new Vector3 to set the value to and just set the individual components.

    transform.position = new Vector3(0, 0, x);
     
    Last edited: Mar 27, 2015
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    It generally helps if you state what the error was.

    But if I recall correctly, transform.position is a property, not a field. That means any time you access it, it looks like you're accessing a variable, but actually behind-the-scenes you're calling a method--either the "get" method, which returns the transform's current position as a Vector3, or the "set" method, which accepts a Vector3 as a parameter and changes the transform's position to match.

    So it should work fine to do this:

    Code (CSharp):
    1. Vector3 temp = transform.position;
    2. temp.z = 0;
    3. transform.position = temp;
    But you can't (or at least shouldn't) say "transform.position.z = 0" because that technically translates to "call a method that returns a Vector3, and then change the z value of the returned value, and then throw away that value because I'm not assigning it to anything".