Is there a shortcut or function to zero out the Y-coordinate of a Vector3?

I’m making a 3D game and I want to know what position my gameObject has on the XZ axis.

I could do:

Vector3 pos = myTransform.position
pos.y = 0;

or:

Vector3 pos = new Vector3(myTransform.position.x,0,myTransform.position.z);

Is there a function in Vector3 to do that, or should I make one myself?

Nothing built in, no. You can certainly make one yourself. I’d use an “extension function” e.g. (uncomplied, example only)

static public class VectorExtensions
{
   static public Vector3 XZPlane(this Vector3 vec)
   {
       return new Vector3(vec.x,0,vec.z);
   }
}

usage

Vector3 XZpos= myTransform.position.XZPlane();

For more details, Bunny83 has posted a complete V3 to V2 extension class on another question: https://answers.unity.com/questions/472825/access-2-of-the-3-components-of-vector3-vector3xy.html?childToView=472884#answer-472884

There is not a straight forward way that I know of no. However there is a workaround you can use.

Vector3.Scale: this method lets you scale the components of one vector by the components of the other.
So if you scaled your transforms position by a vector (1,0,1) then it would kill the Y value and leave the X and Z untouched.

However this then can look odd when skim reading your code later so personally I opted for the root of just writing extension methods for Transform that let me zero out the components individually.

  • one think that u can do is do a
    Constant Vector3 like this public:
    Vector3 ZeroY = new Vector3(1,0,1);
  • and them Multp. the Vector witth the
    transform position:

Vector3 pos = myTransform.position * ZeroY;