3 Spawning enemies with the Prototype pattern

 

This chapter covers

  • Defining, diagramming, and analyzing the pros and cons of the Prototype pattern
  • Implementing shallow and deep object copying with data structures
  • Programmatically cloning Unity prefab objects at runtime
  • Creating and using a generic cloning script component

In the last chapter, we dove head-first into our first design pattern with the Singleton, exposing its strengths, weaknesses, and practical implementations of differing complexity. In this chapter, we’ll learn about how the Prototype pattern helps you specify the kinds of objects you may want to create using a prototypical instance and then making copies of the prototype instead of instantiating new objects. This scenario is common in games where procedural enemies are spawned with a base state and modified without the computational overhead of creating new objects from scratch.

One important concept to keep in mind with the Prototype pattern is how objects are copied in C#, specifically the differences between a shallow and deep object copy. A shallow copy will clone every object field except reference types, while a deep copy will include the objects reference type properties. When we copy objects in Unity, the entire object is duplicated.

3.1 Breaking down the Prototype pattern

3.1.1 Diagraming the pattern

3.2 Implementing shallow and deep object copying

3.2.1 Adding a prototype interface

3.2.2 Making shallow object copies

3.2.3 Making deep object copies

3.2.4 Adding a Prototype factory

3.3 Cloning Prefabs

3.4 Creating a generic prototype Component

3.5 Summary