- Home /
Overload Vector3's operator +
Is is possible to overload Vector3's operator + using C# extension methods? What I specifically want to achieve...
Vector2 vec2 = new Vector3(1,1,1) + new Vector2(1,1); //returns (2,2), truncating the z element
I'm sick of continuously casting Vector2's and Vector3's when working with Unity's 2d feature. Thanks!
Answer by NickP_2 · Feb 04, 2014 at 07:30 AM
Yes this is very possible, take a look here.
I've never used it on a Vector3, but I can't think of something why it wont work, and if so, you can still create your own struct instead of overwriting it!
Hope it helps somehow
I know how to overload an operator.. but what I need is to overload an existing class' operator. Thanks for your reply.
It would seem like the only way to go is to make your own struct, because as far as I know, you can only overload a class' operators from within that class.
The easiest way I can think of to get rid of typecasting altogether, is to make your own struct like Nick said. Let's name it $$anonymous$$yVec2
, which in addition to whatever functionality you need from Vector2, also contains the implicit type cast operator (at least from $$anonymous$$yVec2 to Vector2) and the addition operator.
Now, anything that accepts a Vector2 as a parameter, will also accept $$anonymous$$yVec2 without you explicitly type casting it.
Answer by Owen-Reynolds · Feb 04, 2014 at 02:25 PM
Might be able to achieve the same effect by writing Vector3 addWide(Vector3 v3, Vector2 v2)
... .
Your answer
Follow this Question
Related Questions
Should I use Vector3D in a 2D game? 1 Answer
How to use 2D pathfinding with vector 2 0 Answers
Normalizing a vector 1 Answer
conserve momentum of vector3.moveTowards in 2D game 0 Answers