Introduction to Patterns in Game Development by

 

Design patterns

Design patterns originate as an architectural concept from the 70s, but they really gained popularity with the classic book Design Patterns: Elements of Reusable Code(which, due to its long name and numerous authors, is also often referenced as the book by Gang of Four or GoF) in 1994. In this course we will explore some of the patterns that are most relevant to development of games and we will do this under the guidance of the book Game Programming Patterns. With the exception of the 6. practice session, which is on creational patterns, all other patterns can be found in this book.

So what is a design pattern? The GoF gives the following definition:

“A design pattern systematically names, motivates and explains the general design that addresses a recurring design problem in object-oriented systems. It describes the problem, the solution, when to apply the solution, and its consequences. It also gives implementation hints and examples. The solution is a general arrangement of objects and classes that solve the problem. The solution is customized and implemented to solve the problem in particular context.”

In other words a design pattern offers a vague solutions to recurring problems in object-oriented systems. As games happen to be some of the most complex object-oriented systems and often quite similar to one another, then it only feels natural to try and apply time-tested design patterns to them.

The course exercises will be in C# using the Unity framework. Though we will not be focusing on learning the framework. There are countless written and video tutorials on the internet on how to create a single feature or a system in a specific game engine or framework. Instead we will look at how to make all the different systems fit together neatly into a game.

C# and OOP

For the course it is necessary to understand a few basics of object-oriented programming along with some related syntax in C#. In this chapter you will find a short reminder of OOP basics and some of the C# keywords used during the course.

A complete list of keywords in C#.

Encapsulation

Encapsulation means that group of related properties, methods and other members are treated as a single object. Classes and structures(keyword struct) are a types of object.Objects are usable instances of classes. The act of creating an object is called instantiation and is done with the help of constructors.

Constructors and destructors

Constructors and destructors are special member functions of a class. When an object of a class is instantiated, then one of its constructors is called to initialize the object. Likewise when the object is no longer needed a destructor is called to tidy up. In C# you will rarely need to declare destructors yourself and an empty destructor should never be defined, as it leads to loss of performance. As an example general uses for destructors are to release some unmanaged resource, such as a file lock or a network connection. We will most likely run into destructors during the observer pattern.

public class Game

{

//Constructors are named after the class

public Game()

{

Debug.Log("A game is constructed");

}

//Destructors start with ~

~Game()

{

Debug.Log("A game is destroyed");

}

}

 

MSDN Constructors
MSDN Destructors

Access modifiers

Access modifiers define the accessibility level for a class, interface or struct.

private – accessible only within the body of the class or the struct in which they are declared

protected – accessible within the body of the class or derived class.

public – there are no restrictions to accessing public members.

Inheritance

Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base(or parent) class, and the class that inherits those members is called the derived(or child) class.

//Use : to extend a class or interface in c#

public class MoveCommand : Command

{

}

New and Override

New and override are used to hide or replace methods of parent class.

New – Equivalent of not using a keyword. Preserves the interaction, but suppresses the warning.

Override – Replaces the base method. Only applies to methods that are virtual, abstract or override.

MSDN New and Override

Polymorphism

Polymorphism enables objects of derived classes to be treated as object from the base class. By declaring methods virtual or abstract you can have derived classes override methods from the base class.  

Virtual and abstract

Abstract methods can’t have any functionality. By using an abstract method definition you are saying, that any child class must have this method implemented to function properly, but the problem is too general to be addressed in the parent class.

Virtual methods only difference from non virtual methods is the possibility to be overridden. If a problem is too general to be addressed in parent class, but given function doesn’t necessary have to be implemented in a child, then an empty virtual method can be used in place of an abstract method.

Partial

The partial keyword lets you split a class(struct or interface) across different files, as long as every declaration of the class has the partial keyword. During the course we will occasionally use partial classes to hide away some of the code, which is too Unity specific or would take away too much focus from the design patterns.

Design Patterns in Game Engines

Game development is often preceded by lengthy development of a game engine. Once the studios have a working engine capable of drawing graphics, managing assets and running behavioral scripts, they then proceed to release a number of games on it. Luckily there are now numerous engines available to us, so we can skip the first part and head on to the second part.

We will have a look at Unity through the lense of design patterns. A few patterns are so ingrained in the game development, that they are present in most game engine. We will not be implementing these in the tasks, but instead have a look at them in Unity.

Game loop

Decouple the progression of game time from user input and processor speed.

Game Programming Patterns - Game Loop

Most of the actions taken during one iteration of the loop can be found here

Double Buffer

Cause a series of sequential operations to appear instantaneous or simultaneous.

Game Programming Patterns - Double Buffer

Component

Allow a single entity to span multiple domains without coupling the domains to each other.

In Unity all entities in the game are GameObjects. A game object itself is quite a minimal class. It has a name, a tag, few boolean values, a collection of components and some methods to pass on messages to these components. It is the components that define what the game object is actually capable of.

A game object with camera component would render the scene to the player, a game object with light component would illuminate the scene or a game object with MyAweseomeScript component would do some awesome things that I programmed it to do. We could also have a single game object hold all 3 of these components at the same time as well.

The component pattern offers numerous benefits:

  • It offers much better code reuse than long inheritance trees for every type of game object would.
  • It reduces code coupling, by keeping different domains of single entity separated.
  • It greatly improves performance, if it is implemented with the data locality pattern in mind.

Unity implements component pattern in it’s Component class.

Unreal engine uses Actors and Components. The overall pattern is the same, but slight difference is, that Unreal uses about a dozen different actor types, where Unity would have a GameObject with a component. Eg StaticMeshActor is an GameObject with a static mesh component in Unity. Although since both engines use same pattern and Unreal supports empty Actors, then you can also create an Empty actor with static mesh component.

In XNA/Monogame you can find a GameComponent class, which implements the pattern at the level of main game object itself, while the purpose remains the same.

When learning a new game engine or framework, then looking for a component class is a good place to start.

Game Programming Patterns - Component

Update Method

Simulate a collection of independent objects by telling each to process one frame of behavior at a time.

Along with component pattern and game loop, the update method makes up the 3rd part of the holy game engine design pattern trinity. With the game loop we can break up the time into frames for our game and with component pattern we get to fill our game world with all different kind of entities, except they still can’t actually do anything. We still need to allocate time to all the different scripts for pathfinding, animations, sounds and all kinds of different behaviours. This is where the update method comes in.

To implement the update pattern, we need the game world maintain a collection of objects. Each of these object will implement an update method that simulates one frame of the object’s behavior and each frame, the game will call update on every object in the collection.

In Unity the update pattern can be found inside MonoBehavior class, which in turn extends the Component class. As a MonoBehavior is a component, then this means we can attach a script to any entity in the game world and have our script be called once every frame of the games simulation. To do this we derive a class from MonoBehavior and override the Update(or fixed update) method present there. When doing this, the Unity engine will add your script into a collection of components to be updated every frame.

A number of Unity update methods and other overrideable method hooks can be found under MonoBehavior - Messages

The update method in Unreal Engine is located in Actor class and is named Tick().

Game Programming Patterns - Update

Submitting tasks

  1. Create an Unity package from your project through Assets  Export Package
  2. Upload the package in CGLearn tasks.

Q: What happens if I include the folder "Do not export" folder?
A: The package will be a be slightly larger and export will take slightly longer. "Do not export" folder includes the graphical assets used in the project. There are no tasks that require modifications to these files.

;