- Home /
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?
Answer by Jamora · Oct 09, 2013 at 05:25 PM
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;
This was my initial thought, but I was hoping for an easy #define DISABLE_I$$anonymous$$PLICIT_CAST
or something to that effect. I noticed an ENABLE_DUC$$anonymous$$_TYPING
define in the Editor logs, but I'm guessing that only applies to UnityScript/Boo.
I wonder if this has performance implications for mobile games on low end devices. Anyone has any data on this?
Your answer
Follow this Question
Related Questions
Project a Vector3 onto a plane, orthographically 2 Answers
Rotating A Vector2 Input Into A Vector3 1 Answer
Vector1, Vector2, Vector3? 1 Answer
Convert Vector2 to Vector3 based on the ground's height? 1 Answer
Vector2 Normalize ? 3 Answers