Book Image

Game Development Patterns with Unity 2021 - Second Edition

By : David Baron
Book Image

Game Development Patterns with Unity 2021 - Second Edition

By: David Baron

Overview of this book

This book is written for every game developer ready to tackle the bigger picture and start working with advanced programming techniques and design patterns in Unity. Game Development Patterns with Unity 2021 is an introduction to the core principles of reusable software patterns and how to employ them to build components efficiently. In this second edition, you'll tackle design patterns with the help of a practical example; a playable racing game prototype where you’ll get to apply all your newfound knowledge. Notable updates also include a game design document (GDD), a Unity programming primer, and the downloadable source code of a complete prototype. Your journey will start by learning about overall design of the core game mechanics and systems. You’ll discover tried-and-tested software patterns to code essential components of a game in a structured manner, and start using classic design patterns to utilize Unity's unique API features. As you progress, you'll also identify the negative impacts of bad architectural decisions and understand how to overcome them with simple but effective practices. By the end of this Unity book, the way you develop Unity games will change – you’ll adapt a more structured, scalable, and optimized process that will help you take the next step in your career.
Table of Contents (22 chapters)
1
Sections 1: Fundamentals
5
Section 2: Core Patterns
16
Section 3: Alternative Patterns
20
About Packt

Implementing the Observer pattern

Now, let's implement the Observer pattern in a simple way that can be reused in various contexts:

  1. We are going to start this code example by implementing the two elements of the pattern. Let's begin with the Subject class:
using UnityEngine;
using System.Collections;

namespace Chapter.Observer
{
public abstract class Subject : MonoBehaviour
{
private readonly
ArrayList _observers = new ArrayList();

public void Attach(Observer observer)
{
_observers.Add(observer);
}

public void Detach(Observer observer)
{
_observers.Remove(observer);
}

public void NotifyObservers()
{
foreach (Observer observer in _observers)
{
observer.Notify(this);
}
}
}
}

The Subject abstract class has three methods. The first two, Attach() and Detach(), are responsible for adding or removing an observer object from...