Hands-On Game Development Patterns with Unity 2019

5 (2 reviews total)
By David Baron
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Unity Engine Architecture

About this book

Traditional building blocks of a robust architecture, such as design patterns, cannot be applied in Unity without being adapted to the Engine's unique way of doing things. We will review design patterns that are currently used by professional game programmers in indie, mobile, and AAA studios. We will also examine the infamous anti-patterns.

The book begins by explaining Unity Engine's architecture and shows you how to explore it for designing games. This will help readers get familiar with the pillars of Unity's Engine architecture and assist them in making better technical decisions.

We will then learn about the game industry's most popular software design patterns. Right from the initial concept up to its implementation, you'll learn every detail in the context of genuine industry use cases that game programmers often deal with in the field. This approach will be a onestop reference point and will give you a complete picture of tried and tested software development patterns with Unity using C#.

We will review classic patterns such as Singleton; modern patterns such as Event Bus; and even rare patterns such as the Spatial Partition.

The book concludes by covering the dark side of design patterns, by exposing recognizable patterns that tend to creep out in code bases and have unexpected negative side-effects.

Publication date:
March 2019
Publisher
Packt
Pages
242
ISBN
9781789349337

 

Chapter 1. Unity Engine Architecture

We are about to start on a journey that will teach us how to use software design patterns inside the Unity engine's development environment. This book takes a very hands-on approach to learning and applying design patterns. We are going to avoid getting lost in academic definitions of patterns and instead focus on implementing them with Unity's API on genuine game-development use cases. For those that want to dig deeper into the theory of a specific pattern, at the end of each chapter, there will be references to further reading material.

But the most important note to keep in mind is that this book focuses on simplicity over complexity. That means the code examples and use cases are designed to be as simple as possible so we can concentrate on the essential elements of a pattern, while avoiding getting lost in complex implementations. As a reader, I encourage you to take the source code of each chapter, elaborate on it, and then make it your own.

However, before diving into a new game engine and start coding with its API, it's essential to understand its architecture. So, in this chapter, we will be reviewing the core engineering pillars of the Unity engine. But first, for those that are still new to game development, we are going to quickly discuss the core components that are common to most game engines and how they influence the way we write code for video games.

The following topics will be covered in this chapter:

  • Engine architectures
  • Unity's component system
  • Unity's scripting API

 

 

Engine architectures


In this section, we will review the basic principles behind game engines. Of course, the focus of this book is not about mastering engine architecture. Nevertheless, it's wise to take the time to familiarize ourselves with an engine's core architecture before making a game with it. We don't want to be blindsided later on by technical details that will break our design choices.

What are game engines?

Game engines are what drives the game industry forward, and Unity is the best example of this. Since its release, the number of game studios has grown at an exponential rate. Unity has democratized the process of making video games by offering an extensible development environment for amateurs and professionals alike.

But for those unfamiliar with the concept of game engines, or even why they are called engines, I have a straightforward way to describe them. Look under the hood of your car, what do you see? Cables, filters, tubes, batteries, and gears connected but working in unison to run the vehicle. A game engine is very similar to the concept of a car engine, but instead of being made out of metal and rubber, it's pure software. If you look under the hood, known as the codebase of any modern game engine, you will see hundreds of systems, tools, and components all interconnected and running in unison.

So, if you are planning to produce a video game, the most critical decision you will have to make is what engine you are going to use, because this is what will be running your game. This single choice will influence every aspect of your production. Every department will be required to adjust and alter their pipelines and workflows. Many games have been canceled or have ended up being bug-ridden disasters because of an unwise choice in engine technology.

That's one of the reasons that Unity became so popular, as its name implies, it's an engine that has the core intention of unifying the game industry. You can find Unity being used to build games ranging from Angry Birds clones to epic Japanese Role-playing Game (JRPGs); in other words, it's genre-agnostic. By combining all the best practices of the industry and integrating them into a unique but straightforward development environment, Unity has made its engine a cornerstone of the industry.

Note

Please note that Unity is a closed codebase. Only partners of Unity have direct access to the source code of the engine. So there's a certain degree of speculation when we talk about the inner workings of Unity's architecture. That's why we are keeping this chapter very high-level and not diving too deep into specifications.

 

Unity's architecture


Now it's time to tackle our main subject, Unity and its core engine architecture pillars. One thing we must keep in mind is that Unity is a closed source engine; this means that we have to extrapolate our mental model of its overall architecture from its official documentation. To avoid going into gray areas of Unity's design that cannot easily be validated, we will focus on the most visible and useful pillars for us to know. The two main core engine architecture pillars are as follows:

  • Components
  • Scripting API

Components

Unity is a component-driven engine, and it's with a combination of components that we build our game. If we analyze the following graph, we can see there's a high-level hierarchy that entities contain other entities. The essential elements of this structure are the Components; they are the building blocks of a game:

A simple way to visualize this architecture is to consider that a Scene is a collection of GameObjects, and GameObjects are a collection of Components that can implement and include the following:

  • Systems (cameras and physics)
  • Data (configurations, animations, and textures)
  • Behaviors (game mechanics and scripted events)

 

So with this approach, we can quickly transform a GameObject that's behaving like a camera into an animated character by merely changing the components that it holds. That means that GameObjects are composed of components, and, depending on what type of component we attach to a GameObject, it will morph it into a specific kind of entity such as a camera, animated character, or particle. So it's a very straightforward and modular approach to constructing a game.

In the next section, we will review the API that Unity provides, which permits us to write those various components.

Scripting API

The original designers of Unity understood if they wanted to make an engine that could be used by developers of various skill levels, they needed to design a programming environment that was easy to use, but flexible enough to make any types of game. They achieved this by wrapping and exposing the engine's core functionalities and libraries through a managed scripting API. So, this means that a Unity developer can focus on writing code without worrying about the intricacies of memory management, or the inner workings of the engine.

This approach is common even with AAA in-house engines. The core components of the engine are usually coded in low-level programming languages, like C++ and assembly language because you need precise control over memory and processing usage. But programmers that are responsible for implementing in-game systems, such as AI behaviors or gameplay mechanics, can code on a higher layer of the engine's architecture. So engine programmers will often expose an API or library for gameplay programmers, so they can implement in-game components in a safe and controlled environment.

Gameplay programmers will often implement another layer of abstraction in the form of a simple scripting language, such as LUA, so designers can script behaviors without having to know how to code. Some engines go even further with this approach of simplification by implementing a visual scripting environment; an excellent example of this is Unreal's Blueprint system.

The end goal of all these layers of abstraction is to make the process of building a game more accessible to developers of diverse expertise, but also protect the engine from crashing because of poorly-implemented code. In other words, we want to avoid having a designer crash the engine because he wrote a script that spawns a thousand enemy characters at once in a scene, and as a consequence, causes an insufficient memory exception. So, we want to make sure the API or scripting library, which we offer to those that create content with our engine, can assist them in avoiding provoking critical errors that might affect the overall stability of the development environment.

The following diagram showcases the architectural hierarchy and the chain of responsibility of a typical AAA game development team. As we go up in the chain, technical details become abstracted, and there's a higher level of focus on content creation:

The purpose of this is to control access to the engine's limited resources, while exposing core features to the end user, which are usually designers and artists. And so, Unity's Scripting API has a similar purpose; its objective is to expose Unity's core features to the end user, in this case, developers, while protecting the inner workings of the engine.

 

So, the combination of a scripting API and a component system gives us a very simple, but powerful, coding model in Unity. You can see by the following code example how easy it is to implement a reference to a component of a GameObject and call its public methods:

using UnityEngine;

public class PlayerCharacter : MonoBehaviour
{
    public float m_Range = 10.0f;
    public float m_Damage = 12.0f;

    private Weapon m_Weapon;
    private Inventory m_Inventory;

    void Awake()
    {
        m_Weapon = GetComponent<Weapon>();
        m_Inventory = GetComponent<Inventory>();
    }

    void Start ()
    {
        m_Inventory.Loadout("default");
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            m_Inventory.EquipNextWeapon();
        }

        if (Input.GetKeyDown(KeyCode.Return))
        {
            m_Weapon.Shoot(m_Range, m_Damage);
        }
    }
}

This approach to programming games is straightforward, but also powerful. In this book, we are going to exploit the flexibility of Unity's API and its component driven architecture, while applying classic and modern software design patterns to make our code more robust. Our final goal is to build a toolkit of patterns that are adapted to Unity's unique coding model so we can develop games with a robust architecture.

 

 

Note

For every industry-standard pattern or best practice, there's potential corresponding anti-patterns or drawbacks. It's important as a programmer to keep in mind not just the benefits of implementing a pattern, but also its potential pitfalls if incorrectly integrated into your overall architecture.

 

Summary


In this chapter, we started to explore the world of game engines and two of Unity's core engineering pillars:

  • The component system
  • The scripting API

Engines are very complex pieces of software, Unity has hundreds of features that we won't be able to cover in this book, but if we focus on mastering Unity's API, we will know how to access them when needs be.

In the upcoming chapters, we will focus on architecture, but more specifically, design patterns. We will learn how we can adapt proven industry patterns and best practices into Unity's unique coding model, without falling into the pitfalls of over-engineering. In the next chapter, we will review the two most critical concepts and patterns in game programming, the Game Loop and the Update method, which can be considered the heartbeat and ears of a video game.

 

Further reading


About the Author

  • David Baron

    David Baron is a game developer with over 15 years' experience in the industry. He has worked for some of the top AAA, mobile, and indie game studios in Montreal, Canada. He has a skillset that includes programming, design, and 3D art.

    As a programmer, he has worked on a multitude of games for various platforms, including virtual reality, mobile, and consoles.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Exactly the book I was looking for.
The book arrived in time and in very good condition!

Recommended For You

Book Title
Unlock this full book with a FREE 10-day trial
Start Free Trial