- Home /
Writing Policy class for handling Vector2s and 3s.
I'm finding I have to write a lot of similar code in certain situations for Vector2s and 3s. So, I figured write a generic class that takes a VectorPolicy and does calculations with the appropriate type. The only issue is Vector2s and 3s don't have interfaces backing them. So, I decided to make a policy class that would call the appropriate methods on each. Like so:
public interface IVectorPolicy<T>
{
T Add(T a, T b);
float Dot(T lhs, T rhs);
}
That I'd use like so:
public class Test<T, G> where T : IVectorPolicy, new()
{
readonly T vectorPolicy;
public Test()
{
vectorPolicy = new T();
}
public Foo(G vector1, G vector2)
{
G g = vectorPolicy.Add(vector1, vector2);
float dotProduct = vectorPolicy.Dot(g, vector1);
}
}
But this causes other issues with G not being known at compile time. As far as I'm aware the compiler cannot figure out the Type of a Generic Type being passed to another Generic Type at compile time. Anyone have any idea how I could work around this?
Answer by Owen-Reynolds · Jan 08, 2015 at 06:01 PM
Think you'd get better results in a pure C# forum. The only Unity thing in the Q is Vector2/3, and that should be easily understandable as "2 similar structs" -- and I think most people will recognize them as the more common float2
and float3
types.
My solution was never to use Vector2's. I had some data which was really a worldGrid xz position, so stored it as a Vector2. Figured I'd convert it to (x,0,z) format and back as needed. Was no end of trouble keeping them straight, esp. as V2s cropped up elsewhere that really were xy.
I just put that xz Vector2 attempt under "premature optimization." Of course, I do use V2's for purely grid-based stuff, when I know I'll have one well-marked conversion to and from world coords.
I've looked into the c# answers on this, and it sounds like it requires heavy use of reflection. Thanks for the help.