- Home /
Adding type convertions to unity core types
I wanted to add an conversion between one of my custom types Block
and a unity core type Vector2Int
so that i could write Block John = (Block)vector2Int;
where do i need to put my existent conversion code?
Answer by Bunny83 · Apr 15, 2020 at 01:47 PM
Type conversion operators have to be located in either of the type types. Since you can not modify Unity's Vector2Int struct it has to be in your Block type. Type conversion operators can be implicit or explicit. Operators are always public static methods. It would look something like that:
public class Block
{
public static explicit operator Block(Vector3Int aVec)
{
var b = new Block();
// do whatever you need to do
return b;
}
}
Of course for that matter it's irrelevant if the type is a struct or a class. If you want you can also create the opposite conversion as well
public static explicit operator Vector3Int(Block aBlock)
{
var v = new Vector3Int();
// do whatever you need to do
return v;
}
Be careful with implicit conversions. You should only use implicit operators when the two types really represent the same thing, just in a different type. That's why C# has implicit conversion from int to float or double, but only explicit conversion the other way round. When converting double to float you're loosing precision so it has to be done explicitly while going from float to double there is no issue as a double can represent a float perfectly.
Your answer
![](https://koobas.hobune.stream/wayback/20220612231456im_/https://answers.unity.com/themes/thub/images/avi.jpg)