A Vector is a mathematical object that represents a direction and/or magnitude (length) in 2D or 3D space. Vectors are used extensively in Unity to handle positions, directions, velocities, and other spatial operations. Unity provides several vector types to represent these in different dimensions.
Vector2 – Represents a 2D vector (x, y) for 2D space (e.g., for 2D games or UI positioning).
Vector3 – Represents a 3D vector (x, y, z) for 3D space (e.g., for 3D game objects' positions or directions).
Vector4 – Represents a 4D vector (x, y, z, w), used in more advanced cases like shaders, 3D transformations with homogenous coordinates, and some mathematical operations.
Vector3 v1 = new Vector3(1, 0, 0);
Vector3 v2 = new Vector3(0, 1, 0);
Vector3 result = v1 + v2; // (1, 1, 0)
Vector3 v1 = new Vector3(2, 3, 4);
Vector3 v2 = new Vector3(1, 1, 1);
Vector3 result = v1 - v2; // (1, 2, 3)
Positioning: Objects in the game world are positioned using Vector3 (e.g., transform.position = new Vector3(0, 1, 0);).
Movement: Moving an object in a particular direction, like transform.Translate(Vector3.right speed Time.deltaTime);.
Direction and Rotation: Vectors are often used to represent directions for things like look rotation (transform.forward) or velocity.
Physics: Vectors are crucial in Unity's physics system (e.g., rigidbody.velocity, force, etc.).
void Update()
{
// Move the object up
transform.position += Vector3.up * speed * Time.deltaTime;
}