I’m refactoring the Blueprint code in my game and would like some guidance on optimizing class inheritance. Currently I have three different vehicle types (Pawns), each with a different play style. In addition, each vehicle has its own PlayerController.
I would like to consolidate the redundant logic from the three PlayerControllers into a single parent PlayerController class, which can then be sub-classed. However, inside the PlayerController I need to Get Controlled Pawn, and then cast it to a particular type of Pawn.
Since the Pawn type will vary in the PlayerController sub-classes, how do I handle casting the Controlled Pawn inside the PlayerController? In my experience, the class type is hardcoded in the dropdown menu of the Cast node.
Is there a way to provide an argument to the PlayerController instance so that it knows what to cast the Controlled Pawn to?
So it seems like you know what you’re supposed to do already.
You consolidate the common logic into a base class of sorts (ie Vehicle_BASE) that all the other vehicles inherit from (ie Vehicle_Truck, Vehicle_Sedan).
You then cast to that base class and call whatever functions you want (ie StartVehicle) that are declared in that base class.
The StartVehicle could be overwritten in the derived classes (say if you had a push to start car rather than a key or an electric vehicle depending on what you’re doing with the game) or it could stay default.
There is no way to dynamically cast in blueprints. Though you could make a custom switch statement for classes or use the classic if else * 100.
For the switch statement in the PlayerController class, how would that logic work? One idea is to have an Int in the vehicle parent class, and each derived vehicle sets a different value for that Int (1, 2, 3). Then after casting to the vehicle parent class within the PlayerController, just fetch the Int value from the object returned from the cast, and do a switch on the Int value. This seems rather clumsy/hacky and I wonder if there’s a better solution.
I said that as a hail mary that you weren’t actually supposed to consider.
I still recommend what I said above, but if you really want to do it this way, you can do something like this: