HingeJoint2D and WheelJoint2D in the same List<Joint2D>

Hello,

I have this code that loads all joints that represent wheels and spins their motors to make the “vehicle” moving.

List<Joint2D> wheelsJoints = new List<Joint2D>();
wheelsJoints.AddRange(gameObject.GetComponents<HingeJoint2D>());   wheelsJoints.AddRange(gameObject.GetComponents<WheelJoint2D>());

void DriveVehicleHandler (float speed)
{
    foreach (Joint2D joint in wheelsJoints)
    {
        JointMotor2D motor = new JointMotor2D();
        motor.motorSpeed = (vehicle.Heading == VehicleHeading.left) ? speed: -speed;
        motor.maxMotorTorque = joint.motor.maxMotorTorque;
        joint.motor = motor;
    }
}

It obviously doesnt work as Joint2D has no “motor” property.

What is a nice way to make this code work? Is there a nice clean solution? (Other than using only one type of 2D joint)? Im quite new to OOP and polymorphism.

Thank you!

If you know the exact joint it is you could cast it like so:

var hinge = (HingeJoint2D) joint;

Thank you for suggestion. I know about casting. Problem is that there are both HingeJoint2D and WheelJoint2D in the list of Joint2D thanks to polymorphism so casting fails in some cases.

I can always make two separate lists, one for HingeJoints2D and one for WheelJoints2D but I hoped that there was a better solution.

As I understand it, if both HingeJoint2D and WheelJoint2D inherited from same class that has motor property, my code would work. I hoped that someone could explain a little bit better if there is something I can do.