Problems with code reusability


Reported by: Eldar Bertsel

November 3, 2023

THE PROBLEM

This week I finally got to reorganizing and reworking the player scripts because they are awful. In our game we currently have 3 playable classes with light attack, heavy attack and 3 abilities. In the code that I wrote, each ability and attack is put in a function that will instantiate something. It either instantiates a projectile like a pebble or fireball, or ground pound collider with the visual effect. Then those functions are getting called during the animations by using events. It might sound like an good idea to do it this way but it is really bad because now I have somewhere about 20 functions that are all unique and only work for specific ability or attack and only in specific places because I have 3 different spawn points. This creates a problem incase we as a team decide that we want to swap abilities and attacks or change the ability completely, because if we do that then I have to delete old functions and create new unique functions that will again only work for that ability or attack.

THE SOLUTION

Because reusability and clean code are very important I started searching for ways to make the code, well... reusable and clean. I spend a bunch of time looking at other people's code to get some ideas and finally found something that makes the most sense for our game. 

First, instead of using events in the animations I now use StateMachineBehavior derived script that is basically a script that will be called during specific time when the animation is played. That script has a function with 2 parameters, which hand to spawn the ability at and at what time of the animation. And the only thing it does it calls a function that will instantiate the ability that was just used by the player.


Second, instead of having all of the special effects and models of the abilities and attacks serialized in one script, I now use the scriptable objects of our weapons and abilities who now have model and effect fields on them. Also, I made an event that will check when the player uses a certain ability and attack, then I wait for that to happen and when that happens I change the model and effect. This way you just need to have a script on the player and it itself will find all of the models and effects that should be instantiated.  


Third,  instead of having multiple functions that will instantiate something now have just 2 functions. One to instantiate a model and one to instantiate an effect. It takes 2 parameters, which are which hand to spawn the ability at and at what time of the animation. 

With those changed I can now create ANY ability and attack. The only thing I would have to do is add model and an effect to the scriptable object and add script to the animation.

Get Psyche