Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Game Development Patterns with Unity 2021 - Second Edition

You're reading from  Game Development Patterns with Unity 2021 - Second Edition

Product type Book
Published in Jul 2021
Publisher Packt
ISBN-13 9781800200814
Pages 246 pages
Edition 2nd Edition
Languages
Author (1):
David Baron David Baron
Profile icon David Baron

Table of Contents (22) Chapters

Preface 1. Sections 1: Fundamentals
2. Before We Begin 3. The Game Design Document 4. A Short Primer to Programming in Unity 5. Section 2: Core Patterns
6. Implementing a Game Manager with the Singleton 7. Managing Character States with the State Pattern 8. Managing Game Events with the Event Bus 9. Implement a Replay System with the Command Pattern 10. Optimizing with the Object Pool Pattern 11. Decoupling Components with the Observer Pattern 12. Implementing Power-Ups with the Visitor Pattern 13. Implementing a Drone with the Strategy Pattern 14. Using the Decorator to Implement a Weapon System 15. Implementing a Level Editor with Spatial Partition 16. Section 3: Alternative Patterns
17. Adapting Systems with an Adapter 18. Concealing Complexity with a Facade Pattern 19. Managing Dependencies with the Service Locator Pattern 20. About Packt 21. Other Books You May Enjoy
Concealing Complexity with a Facade Pattern

The Facade pattern is an easy pattern to grasp because its name implies its purpose. The primary intent of the Facade pattern is to offer a simplified front-facing interface that abstracts the intricate inner workings of a complex system. This approach is beneficial for game development because games are composed of complex interactions between various systems. As a use case, we will write code that simulates the behavior and interactions of a vehicle's engine core components and then offers a simple interface to interact with the overall system.

The following topics will be covered in this chapter:

  • Understanding the Facade pattern
  • Designing a bike engine
  • Implementing a bike engine
  • A basic implementation of a vehicle's engine with the Facade pattern
This section includes a simplified version of the implementation of an engine...

Technical requirements

Understanding the Facade pattern

The Facade pattern's name is analogous to the facade of a building—as the name implies, it's an exterior face that hides a complex inner structure. Contrary to building architecture, in software development, the goal of a facade is not to beautify; instead, it is to simplify. As we are going to see in the following diagram, an implementation of the Facade pattern is usually limited to a single class that acts as a simplified interface to a collection of interacting subsystems:

Figure 15.1 – Unified Modeling Language (UML) diagram of the Facade pattern

As we can see in the preceding diagram, EngineFacade acts as an interface to the various components of the engine, thereupon the client is unaware of what is happening behind the scenes when calling StartEngine() on EngineFacade. It's unaware of the components that make up the engine and how to reach them; it only knows what it needs to know. This is similar...

Benefits and drawbacks

Here are some benefits of the Facade pattern:

  • Simplified interface to a complex body of code: A solid Facade class will conceal complexity from a client while providing a simplified interface to interact with an intricate system.
  • Easy refactoring: It's easier to refactor code that's isolated behind a Facade because the system's interface remains consistent to the client while its components are being modified behind the scenes.

The following are some drawbacks to watch out for:

  • It makes it easier to hide the mess: Using the Facade pattern to hide messy code behind a clean front-facing interface will defeat the pattern's core benefits in the long run, but this pattern does offer a way to mask some code smells until you have time to refactor them. However, expecting to have enough time later to fix stuff is a trap in itself because we rarely have enough time to refactor things correctly.
  • Too many facades: Globally accessible...

Designing a bike engine

We are not aiming to implement a complete simulation of an actual gas engine for a bike; this will take too long and demands an in-depth understanding of the physics and mechanics of a real-world engine. But we will aim to simulate, to a minimal degree, some standard components of a high-speed vehicle's motor. So first, let's break down the expected behavior of each part of our engine, as follows:

  • Cooling system: The cooling system is responsible for making sure the engine is not overheating. When the turbocharger is activated, the cooling system shuts down during a turbocharge. This behavior means that if the player overuses the turbocharger, this can overheat the engine, and in consequence, the engine will stop or explode and the bike will stop moving.
  • Fuel pump: This component is responsible for managing the fuel consumption of the bike. It knows the amount of gas remaining and stops the engine if it runs out of it.
  • Turbocharger: If the turbocharger...

Implementing a bike engine

As we are going to see, the Facade pattern is straightforward, so we will keep the following code example simple and straight to the point. To start, we will write the classes for each of the core components that make up the bike's engine, as follows:

  1. We will start with the fuel pump; the purpose of this component is to simulate the consumption of fuel so that it knows the amount remaining and shuts down the engine when it runs out. Here's the code you'll need:
using UnityEngine;
using System.Collections;

namespace Chapter.Facade
{
public class FuelPump : MonoBehaviour
{
public BikeEngine engine;
public IEnumerator burnFuel;

void Start()
{
burnFuel = BurnFuel();
}

IEnumerator BurnFuel()
{
while (true)
{
yield return new WaitForSeconds(1);
engine.fuelAmount -= engine.burnRate;

if (engine.fuelAmount <=...

Testing the engine facade

We can quickly test the code we just implemented by adding the following client script to a GameObject in an empty Unity scene:

using UnityEngine;

namespace Chapter.Facade
{
public class ClientFacade : MonoBehaviour
{
private BikeEngine _bikeEngine;

void Start()
{
_bikeEngine =
gameObject.AddComponent<BikeEngine>();
}

void OnGUI()
{
if (GUILayout.Button("Turn On"))
_bikeEngine.TurnOn();

if (GUILayout.Button("Turn Off"))
_bikeEngine.TurnOff();

if (GUILayout.Button("Toggle Turbo"))
_bikeEngine.ToggleTurbo();
}
}
}

In the client class, we see that it's not aware of the engine's inner workings, and this is the effect we want to achieve when using the Facade pattern. The only thing the client class knows is that it can start and stop the engine and toggle on a turbocharged...

Reviewing alternative solutions

There are several alternatives to keep in mind before considering the Facade pattern, depending on what you are actually trying to accomplish. These are listed here:

  • Abstract Factory pattern: If you only want to conceal how subsystem objects are initialized from the client code, you should consider using the Abstract Factory pattern instead of the Facade pattern.
  • Adapter: If you are intending to write a "wrapper" over existing classes with the intent to bridge two incompatible interfaces, then you should consider using the Adapter pattern.

Summary

Even though the Facade pattern is sometimes used to hide messy code, when you use it as intended, it can enhance your code base's readability and usability by masking underlying complex interactions of subsystems behind a singular front-facing interface. Thus, it's a pattern that can be very beneficial for game programming, but one to use wisely and with good intent.

In the upcoming chapter, we will explore a pattern named Service Locator, which we will use to manage global dependencies and expose core services.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Game Development Patterns with Unity 2021 - Second Edition
Published in: Jul 2021 Publisher: Packt ISBN-13: 9781800200814
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}