Is it possible to have a class's variable correspond to either a BoxCollider2D or CapsuleCollider2D in order to reuse the class for objects with either type of collider?

I have a class that I use on multiple objects. So far the objects have all had box colliders, but I’ve got one that now has a capsule collider. The variable for the collider is used throughout the class, so I’d prefer to be able to use the same variable whether it is a BoxCollider2D or CapsuleCollider2D. Is it possible to change the variable’s type depending on which type of collider the object has?

I tried to use two separate variables of each type of collider (named colliderBox and colliderCapsule) that each GetComponent() of their collider types, then I checked to see which isn’t null to determine if a bool (named hasBoxCollider) is true or false. Then throughout the class, I replaced the collider variable with:

(hasBoxCollider ? colliderBox : colliderCapsule)

Which doesn’t work because “Type of conditional expression cannot be determined because there is no implicit conversion between UnityEngine.BoxCollider2D and UnityEngine.CapsuleCollider2D.” So I’ve now learned that I must use variables of the same type or at least convertible between each other when using x ? y : z. Didn’t know that until now.

I’m wondering if there is any possible way to go about this without a separate class or tons of if statements. Possibly with generics or custom colliders?

Examine the documentation for Collider2D. Ask yourself if your requirements for the colliders fits entirely within the Collider2D interface. If it does, you can stop considering which collider is involved, and make the reference type a Collider2D instead of a BoxCollider2D, and be done.

If, however, that isn’t sufficient, you have a few ways to think of this. You can fashion two scripts, one for Box and the other for Capsule, which are basically empty classes, but derive from your existing class refactored as a generic, where the generic parameter is the collider type you require. If you get that right, you’re done.

It might turn out that while you require a few methods from Box when it’s a box, and a few methods from Capsule when its a capsule, but for most of the code you only need the Collider2d methods, you might consider using a Collider2d reference overall, but just cast in those few cases where you must act based on which you require. You might fashion your existing class as an abstract base which then uses derivatives to override those few places with casts, leaving the rest of your code as is from a Collider2D perspective.