unity3d Vector3 Creating a Vector3


Example

A Vector3 structure can be created in several ways. Vector3 is a struct, and as such, will typically need to be instantiated before use.


Constructors

There are three built in constructors for instantiating a Vector3.

ConstructorResult
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.


Converting from a Vector2 or Vector4

While 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);
}

Debug output confirms that both Vector2 and Vector4 have been successfully converted to Vector3.