- Home /
How are Vector2 and Vector3 interchangeable from a code standpoint
Title says it all, from a code perspective, how were Vector2 and Vector3 made interchangeable. Is it an implicit cast? An inheritance thing?
Simple code example of how they achieved it would be appreciated.
Answer by TobiasW · Mar 27, 2016 at 11:12 AM
Implicit and explicit casting is made possible by defining conversion operators. Here is a pretty good description with an example for both: https://msdn.microsoft.com/en-us/library/85w54y0a.aspx
To add to this answer, link to the docs of these operators.
ps. the Vector3 to Vector2 is at a strange location in the docs, this is probably because the docs are generated, and sinse operators are static they don't have to be placed at a location that makes sense. So Unity placed the operator in the Vector2 class ins$$anonymous$$d of the Vector3 class :p
As for the code used, probably something like this:
public static implicit operator Vector2(Vector3 other)
{
return new Vector2(other.x, other.y);
}
public static implicit operator Vector3(Vector2 other)
{
return new Vector3(other.x, other.y, 0f);
}
Aso on a small sidenote, when implementing implicit operators yourself, the Vector3 to Vector2 might not be a good example, because it loses data. Whenever you lose data in the conversation you generally want to use an explicit operator. (see implicit docs)
Just to add that casting is all good but to be perfectly frank here, when the need arises to convert from one to the other it usually follows that you require a manual conversion.
The linked $$anonymous$$ethods both utilise x and y and z is discarded or zeroed.
$$anonymous$$ost of the time I have required to convert a Vector3 to a Vector2 it is usually that I require the x and z axes and want to ignore the y, so I have no choice other than a manual conversion.
Vector2 myVec2 = new Vector2(myVec3.x, myVec3.z);
This happens a lot when using ScreenPoint to find the coords on a terrain, for example, when the y position is largely unused.
Its a productive day when I learn something new about C# Thanks all for your thoughts, much appreciated. :D
Your answer
