Prevent implicit cast from Vector3-Vector2

Unity provides implicit casts between most of the Vector classes. This is nice in most situations, but is making debugging a nightmare for some of my code. I wrote conversion methods that accept an Axis parameter which allows the user to specify which values to use when converting between Vectors. Ex:

Vector2 myVec2 = new Vector3(1, 2);
Vector3 myVec3 = myVec2.ToVector3(Axis.Y, 0f);    // myVec3 == [1, 0, 2]
Vector2 andBack = myVec3.ToVector2(Axis.Y);       // now is [1, 2] again
Vector2 implCst = myVec3;                         // I'd like this to throw an exception

The trouble is that if I forget to cast, or incorrectly apply math between Vector3 and Vector2 (which is allowed because of implicit casting) variables I get incorrect values.

I’d like to disable implicit conversions for just the Vector classes. Is this possible?

I don’t think it’s possible with C#, with Boo and UnityScript you could possibly do some metaprogramming magic to make it work. I wouldn’t know.

Instead of changing Unity’s implementation, you should create your own implementation of Vector2 & 3. You could then create new MyVectors from Unity’s Vectors, operate on those, then convert them back to Unity’s Vectors.

public struct MyVector2{

    float x,y;

    public MyVector2(Vector2 v2){
        x = v2.x;
        y = v2.y;
    }
    public static MyVector2 operator *(float d, MyVector2 a)
    {
        return new MyVector2(a.x * d, a.y * d);
    } 

    public static implicit operator MyVector2(Vector3 v)
    {
        return new MyVector2(v.x, v.z);
    }

    public static implicit operator MyVector2(Vector2 v)
    {
        return new MyVector2(v.x, v.y);
    }

    public static implicit operator Vector3(MyVector2 v)
    {
        return new Vector3(v.x, 0f, v.y);
    }

    //etc...

}

Now you just need to start operating on your own Vector implementation:

MyVector2 vec2 = transform.position;
transform.position = vec2 * 5.5f;