Design Pattern in Unity3D #0 - Overview
Game programming is also one of the example of Software Engineering where we have to keep maintaining the code all the time and prevent any bugs/errors to occur.
It is an easy thing to do, if the project and the code is not big. The question is, how do we maintain a big project (e.g GTA clone game project) that is so big that have, let's say, 100 classes for the gameplay, 50 classes for the main menu & UI, and so on? If there is a bug, are we be able to immediately found where the bug is currently located? Yes we can, but it will take a lot of time to find and fix it, and not to mention that we will create another bugs once we fixed that particular bug.
Why is that? It is commonly caused by a bad software design, which also includes bad object-oriented design.
So how to solve or even prevent that problem from occuring in our game project?
One of the solution is to implement what is called Design Pattern. What is that? Design Pattern is a reusable solution to a common problems in software design, especially in object-oriented design. So given an object-oriented problem, it will systematically create a design of the solution for that particular problem.
Can we use design pattern in game programming? The answer is Yes we can, or perhaps we must, because game programming uses object-oriented programming most of the time. So we need to have a good object-oriented design in order to keep the code clean and maintainable.
Now, we will see some of the design patterns that is used commonly in game programming.
Observer Pattern, a pattern that can make an object be able to notify other objects whenever it changes its states/attributes. Example of the usage in game is the player's UI elements.
Decorator Pattern, a pattern that can add some additional functionalities to an object. Example of this would be in a hack and slash game where the sword can have some additional effects like stun, critical strike, or slow once it hits the enemy.
Strategy Pattern, a pattern where multiple classes that share a common interface/subclass can have different behaviour & functionality. The example of this would be items in player inventory or player's skill. All of them have a unique passive and active behaviour.
Factory Pattern, a pattern to create objects of classes that share the same subclass/interface, and hides the creational logic. This is common because in most cases, objects in a game are respawnable. The example would be in an endless survival game, where we want to continuously create different types of zombies.
Singleton Pattern, a pattern to limit the amount of instance of a particular class to at most one instance. Example of this would be, let's say, instance of GameWorld class with gravity and timescale variable in it. It doesn't really necessary to have to have multiple game worlds unless its a game where the player can travel to other world.