Unity: Convert Vector2 to Vector2Int

Refresh

April 2019

Views

149 time

1

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();

3 answers

0

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.

0

But is there a shorter or more effective way?

Unfortunately, there is no better solution.

See Unity3d source code: Vector2d and Vector2dInt.

Only back conversion is possible:

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

You can use extension methods to make it more readable:

public static Vector2 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();