Monday, January 21, 2013

Down With OOP

While my job slowed this project way down, I do manage to fire up Unity at least every few days and I'm still making progress on this game, although at this point it would be hard to tell from looking at subsequent builds, because I've finally decided to refactor some code.

I feel like I've been through a small level-up experience. It started about two weeks ago, trying to finish the interaction between the player and the first enemy. I had a small "Kick" function in both playerControls.cs and enemyControls.cs that would apply an impulse to either character when they came in contact with a "bad" object. The function was slightly different for each, but contained some repeated code. I then got into making a "Flash" function to flip a character's sprite renderer off and back on, separated by a tenth of a second coroutine yield, to give that classic effect of a character strobing to indicate they've been injured. I realized that this function would be identical between the characters, which made me look closer at the animation functions for each and realize I was basically writing a really long, complex script twice, simultaneously, changing a few variables and conditionals each time. It had to stop.

Thankfully,'s Prof. Allerdice had provided me with the answer: Inheritance. I made an abstract  "Character" class that implemented all the major functions for all characters, then subclasses "Enemy" and "Player" to break out specific behaviors like patrolling, etc. by overriding virtual functions. The result is a much cleaner working environment, where the Player and Enemy scripts are both clear and compact, and I never really have to touch the Character script. Also much lower bug rate and general stress rate from trying to implement the same thing twice each time.

I have all the bits and pieces of Death together, save for the enemy's "crumbling into bones" animation, so next it's time to tie all that together, then move on to loot and pickups. I can't see the end yet but I think maybe I see the middle out there somewhere.

No comments:

Post a Comment