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);
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:
Vector3 temp = transform.position;
temp.z = 0;
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”.