- Home /
How do I use the Vector2/Vector3 operator (converting Vector2 to Vector3 and vice versa)
The Unity reference describes the following for converting a Vector2 to Vector3.
*Vector2.operator Vector3
static implicit function Vector3 (v : Vector2) : Vector3 Description Converts a Vector2 to a Vector3.
Vector2s can be implicitly converted to Vector3 (z is set to zero in the result).*
I've played around with this a bit, but I'm not sure how to get it working - could someone show me an example.
Answer by Jessy · Oct 11, 2010 at 09:30 AM
It means you can do stuff like this:
var o1o : Vector3 = Vector2(0,1); // UnityScript
Vector3 o1o = new Vector2(0,1); // C#
(However, you can also get the same result from using the "xy" Vector3 constructor):
var o1o : Vector3 = Vector3(0,1); // UnityScript
Vector3 o1o = new Vector3(0,1); // C#
This kind of thing starts to become helpful when you have functions that take a Vector3 as a parameter, but you're only working in 2D. For example, maybe you want to create a UV transformation matrix with Matrix4x4.TRS. In that case, the position variable is only going to be a Vector2, as UV space is two-dimensional. So, despite the fact that the function requires a Vector3, you can send it a Vector2 without any problem.
Thanks Jessy. It was the exact syntax I wasn't sure of - I couldn't deduce it from the reference text.
"Helpful" unless your 2D world is in the x-z plane, and you want the conversion from Vector3 to Vector2 to extract x and z. Of course you can still do the conversion manually, but coding errors can get silently hidden by Unity's automatic conversion.
Answer by roberto_sc · Apr 19, 2015 at 10:17 PM
That means they have overloaded the attribution operator "="; therefore you can simply attribute a Vector3 to Vector2 and vice-versa.
Vector2 v2 = Vector3.one;
Vector3 v3 = Vector2.one;
You don't even need to cast.
Answer by luislodosm · Mar 20, 2017 at 02:41 PM
public Vector2 myVector2D;
public Vector3 myVector3D;
Vector2 myResult2D = myVector2D + (Vector2) myVector3D;
Vector3 myResult3D = (Vector3) myVector2D + myVector3D;