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?