I have a method which takes an interface type and evaluates what the type is and from that I need to return a type related to it. But I'm not sure how to make the type returns flexible for it. I tried something like this:
public static T GridPosition <T>(IReSizeableGrid gridData) {
if (gridData is Hex) {
var hexGrid = (HexGrid) gridData;
return HexLibrary.WorldToHex(WorldPoint(Input.mousePosition, GroundPlane), hexGrid);
}
if (gridData is QuadGrid) {
var quadGrid = (QuadGrid) gridData;
return Grid.Get(WorldPoint(Input.mousePosition, GroundPlane), quadGrid);
}
throw new Exception("Wrong type passed to GridPosition: " + gridData.GetType());
}
But I get this error:
Cannot implicitly convert type
Hex to T
Am I on the right lines here using T
? Trying to understand how to use it properly.
Sometimes generics aren't the right answer. You'd only use generics if you want to do the same thing to two or more related types. In this case, you are doing completely different things, so you actually need to use method overloading instead.
public static Point GridPosition(HexGrid gridData)
{
return HexLibrary.WorldToHex( WorldPoint( Input.mousePosition, GroundPlane), gridData);
}
public static Point GridPosition(QuadGrid gridData)
{
return Grid.Get(WorldPoint(Input.mousePosition, GroundPlane), gridData);
}
You can call either of these with the same code:
var result = GridPosition(new HexGrid());
var result = GridPosition(new QuadGrid());
...and the compiler will pick the right version for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With