A Vector3 structure can be created in several ways. Vector3 is a struct, and as such, will typically need to be instantiated before use.
There are three built in constructors for instantiating a Vector3.
| Constructor | Result |
|---|---|
new Vector3() | Creates a Vector3 structure with co-ordinates of (0, 0, 0). |
new Vector3(float x, float y) | Creates a Vector3 structure with the given x and y co-ordinates. z will be set to 0. |
new Vector3(float x, float y, float z) | Creates a Vector3 structure with the given x, y and z co-ordinates. |
Vector2 or Vector4While rare, you may run into situations where you would need to treat the co-ordinates of a Vector2 or Vector4 structure as a Vector3. In such cases, you can simply pass the Vector2 or Vector4 directly into the Vector3, without previously instantiating it. As should be assumed, a Vector2 struct will only pass x and y values, while a Vector4 class will omit its w.
We can see direct conversion in the below script.
void VectorConversionTest()
{
Vector2 vector2 = new Vector2(50, 100);
Vector4 vector4 = new Vector4(50, 100, 200, 400);
Vector3 fromVector2 = vector2;
Vector3 fromVector4 = vector4;
Debug.Log("Vector2 conversion: " + fromVector2);
Debug.Log("Vector4 conversion: " + fromVector4);
}