'Unity: Convert Vector2 to Vector2Int

I have a Vector2 and I want to convert it into a Vector2Int. I know I could convert the Vector2 with something like this:

Vector2 v2 = new Vector2(10, 10);
Vector2Int v2i;

v2i = new Vector2Int((int) v2.x, (int) v2.y);

But is there a shorter or more effective way? For example something like this:

v2i = v2.toVector2Int();


Solution 1:[1]

There is a built-in static method for this:

Vector2 v2 = new Vector2(10, 10);
Vector2Int v2i = Vector2Int.RoundToInt(v2);

You can also use Vector2Int.CeilToInt(Vector2 v) and Vector2Int.FloorToInt(Vector2 v) depending on what you need

Solution 2:[2]

You can use extension methods to make it more readable:

public static Vector2Int ToInt2(this Vector2 v)
{
    return new Vector2Int((int)v.x, (int)v.y);
}

And use it like this:

Vector2 v2 = new Vector2(10, 10);
Vector2Int v2i = v2.ToInt2();

Solution 3:[3]

You can use the automapper library and let the library do the job for you. The call would be something as:

Vector2Int v2i = Mapper.Map<Vector2>(v2);

The advantage of automapper is, that it is a very powerful tool that hides all this nasty mapping logic for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ImR
Solution 2
Solution 3 StefanG