Based on the information you provided in the comment section, here is a detailed explanation of what was wrong with your code (BP scripts). Simply put, you were violating the polymorphism principles in your code. Polymorphism doesn’t work in the way that you were attempting to do, i.e. it cannot simply cast a Parent class to its children and call their members! Polymorphism requires that you properly design your classes and define their inheritance relationship as well as determine which member functions can be overridden and are therefore virtual! Below is a step by step guide on how to properly use this technique with blueprints and achieve what you want:
-
Start by creating a parent class blueprint for your AI Pawns. Open its BP editor, create a function and name it Attack. Add any input/output pins that you want! This will be the signature of your Attack function which must be exactly the same for its children in terms of the number of input/output pins and their types. You can also implement the base attack logic that is common between all your AI’s in here. This will reduce the amount of duplicate code that you will be having. You can also leave it blank if you want to!
-
Using this parent class, create some child BP that will be your AI pawn (If you already have your AI pawn classes, then make sure that they are inheriting from this parent class). Next, open the child’s BP editor, on the left side next to the New Function button, select Override and from the drop-down menu select the Attack function that we created in Step #1 in the parent class. You should get an Event Attack node with the same number of input/output defined in the parent class. Use this event node to implement your AI attack logic.
-
Now, in order to enable the behavior tree for your AI’s, you must use their AIControllers. Simply go to your AIController, use the BeginPlay node and run the behavior tree you want.
-
Finally, go to the behavior tree and open the Attack task. Note that since a behavior tree can only be run by a controller, that Other Actor pin in your Event Receive Tick represents the controller that initiated this behavior tree. This controller is your AIController from step #3. Use this Other Actor pin and Cast to your AIController > Get Controlled Pawn > Cast to the Parent BP class > Call Attack function of the parent. That’s it! Since you’ve overridden your parent’s Attack function in its children, the parent will automatically call its children’s Attack function so you wouldn’t have to cast to each of them separately!
There you have it. Polymorphism in Blueprints! Follow these steps exactly as I explained and your AI logic should now work in a much neater and cleaner way.