I'm trying to write some kind of utility library in C# but I want to be able to use it with unity or without it. The problem is that there is no provided cast from any UnityEngine math types to System.Numerics math types. Is there any way to define such cast, or do I have to write my own vector2, vector3, etc. classes with casts to both parties?
1 Answers
Since you cannot modify any of the types involved (e.g. System.Numerics.Vector2
and UnityEngine.Vector2
), you cannot create an implicit operator for converting between them.[1]
Instead what you could do is to create overloaded extension methods to convert from one to the other with standardized names ToUnity()
and ToNumerics()
, for instance:
public static class VectorExtensions
{
public static UnityEngine.Vector2 ToUnity(this System.Numerics.Vector2 vec) => new UnityEngine.Vector2(vec.X, vec.Y);
public static System.Numerics.Vector2 ToNumerics(this UnityEngine.Vector2 vec) => new System.Numerics.Vector2(vec.x, vec.y);
public static UnityEngine.Vector3 ToUnity(this System.Numerics.Vector3 vec) => new UnityEngine.Vector3(vec.X, vec.Y, vec.Z);
public static System.Numerics.Vector3 ToNumerics(this UnityEngine.Vector3 vec) => new System.Numerics.Vector3(vec.x, vec.y, vec.z);
// Add others as required.
}
Then whenever you need to convert from one framework to the other, use vector.ToUnity()
or vector.ToNumerics()
as appropriate.
While you will still need to create the conversion methods, this saves you the work of creating your own vector2, vector3, etc. classes.
[1] For confirmation see this answer by Marcel to user-defined conversion must convert to or from the enclosing type. If you try, you will get a compilation error
User-defined conversion must convert to or from the enclosing type

- 104,963
- 20
- 228
- 340