How To: Class Inheritance Amongst Similar Objects


Hello everyone!

During development, I found myself working on objects such as doors and drawers that the player will be interacting with in game. There were many ways to do animations, sounds, and finding out if the item was locked or closed/open, but I was trying to figure out how to compress everything together and make it duplicatable. This will make it very easy to just plop in objects when creating levels. Having a strong framework at the beginning will significantly decrease time during our polish phase for beta.

I first set up the code to be inside our function of the player itself. This turned out to be a huge chunk of performance, as it was having to get so many components and reference singletons just to do one thing. This also doesn't help out with any special parameters that each object would uniquely have.

I then thought of creating a new class for those types of objects. I called it "Interactive Object".  As you see below it would then be able to house all the necessary variables I would need to access at runtime. This was a great start and I then started writing functions to play sounds and animations directly from the object. I then found out that this would not be able to work for different objects efficiently, as for example, the drawer would play and run a different animation then the door would. The protected security allows other classes that inherit from this parent class to access the variables where anywhere else, they would not be able to.

Notice the property set up for "IsLocked". This will allow other classes to reference the variable. Since I only allowed it to get the variable, any other outside class will not be able change the value.

I thought well this would be a great time to use class inheritance where each object would pull the parameters they all would share, but then be able to house their own functions separately from one another.

I created the "Door" and "Drawer" child classes. See them below.

Now they are both allowed to run their different animations and call the AudioManager singleton instance to run the correct sound. If you thought to yourself "well since they both have the same functions, couldn't that be just be in the parent class as well?". Absolutely. In the polishing phase, this will be on my agenda to address immediately. 

The important aspect to recognize is that there are so many ways to do the same thing in code. However, when producing a larger game, you will need to be able to write efficient code that will not produce performance issues in the long term. This of course only comes with experience and practice.

Thank you all for reading!

-Alexander Beifeld

Get Searchlight Hotel

Leave a comment

Log in with itch.io to leave a comment.