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
Implementing a Level Editor with Spatial Partition

In this chapter, we will explore the concept of spatial partitioning. Unlike in previous chapters, the main subject is not traditionally defined as a software design pattern but more as a process and a technique. But because it offers us a reusable and structured approach to solving recurrent game-programming problems, we will treat it as a design pattern in the context of this chapter.

The approach we are going to take in this chapter is different from previous chapters for the following specific reasons:

  • We are taking a hands-off approach; in other words, we will not attempt to implement a code example but will instead review some code segments. 
  • We will not try to stay faithful to any academic definition but will instead use the general concept of spatial partitioning to build a level editor for our racing game.

The...

Technical requirements

We will also be using the following specific Unity engine API features:

  • Stack
  • ScriptableObjects

If unfamiliar with these concepts, please review Chapter 3A Short Primer to Programming in Unity.

The code files of this chapter can be found on GitHub at the following link: https://github.com/PacktPublishing/Game-Development-Patterns-with-Unity-2021-Second-Edition/tree/main/Assets/Chapters/Chapter13.

A Stack is a linear data structure with two primary operations: Push, which adds an element on top of the stack, and Pop, which removes the most recent element from the top.

Understanding the Spatial Partition pattern

The Spatial Partition pattern name comes from the process known as space partitioning, which plays an integral part in computer graphics and is often used in ray-tracing rendering implementations. The process is utilized to organize objects in virtual scenes by storing them in a space-partitioning data structure such as a binary space partitioning (BSP) tree; this makes it faster to perform geometry queries on a large set of three-dimensional (3D) objects. In this chapter, we will use the general concept of spatial partitioning without being faithful to how it's usually implemented in computer graphics.

A very high-level and conceptual way of visualizing spatial partitioning is with the following diagram:

Figure 13.1 – A diagram that illustrates spatial partitioning on a map

The first example represents the position of enemies on the map without any partitioning. If we want to quickly look up the location of enemies in relation...

When to use the Spatial Partition pattern

3D programming is beyond the scope of this book, yet the most important takeaway of the description of spatial partitioning is that it offers a solution to organizing a large set of objects in a scene in an optimal manner. Therefore, if you find yourself needing a quick way to query an extensive collection of objects in a scene while keeping track of their spatial relations, keep in mind the principles of spatial partitioning.

In the next section, we will review the overall design of the level editor and examine its technical requirements.

Designing a level editor

When working on a multi-disciplinary game development team, the responsibilities of a game programmer are not limited to implementing cool game mechanics and features. We are often tasked with building asset-integration pipelines and editing tools. The most common tool we might need to implement early on in a production cycle is a custom level editor for the level designers on our team.

Before writing a single line of code, we need to keep in mind that our game has no randomness integrated into its core game systems. It's a game of skill in which players have the primary goal of reaching the top of the leaderboard by memorizing each track's intricacies and getting to the finish line as fast as possible.

Thus, based on these core design pillars, we can't use a solution such as procedural generation maps that spawn random obstacles based on specific rules and constraints. Consequently, the level designers in our team will have to design the layout...

Implementing a level editor

In this section, we will review some code that will implement the core components of our level editor. Unlike in previous chapters, we will not try to make this code runnable or testable. Instead, we will review the implementations to understand how we use the general idea of spatial partitioning to build a functional level editor for designers while optimizing the way we load levels at runtime.

The code presented in the next section is to be reviewed but not compiled, as it's not a complete self-contained example.

Steps for implementing a level editor

  1. To start, we are going to write a ScriptableObject class named Track, as follows:
using UnityEngine;
using System.Collections.Generic;

namespace Chapter.SpatialPartition
{
[CreateAssetMenu(fileName = "New Track", menuName = "Track")]
public class Track : ScriptableObject
{
[Tooltip("The expected length of segments")]
public float segmentLength;

[Tooltip("Add segments in expected loading order")]
public List<GameObject> segments = new List<GameObject>();
}
}

With this ScriptableObject class, our level designers will be able to design new variations of race tracks by adding segments into a list and then sequencing them in a specific order. Each track asset will be fed to the TrackController class, which will spawn each segment automatically and in the order that the designers sequenced them.

For the player, this process is seamless as it runs in the...

Using the level editor

You can play with the level editor by opening up the /FPP folder in the Git repository and then do the following:

  • Under the /Scenes/Gyms folder, you should find a scene named Segment. In this scene, you will be able to edit and create new segment prefabs.
  • Under the Assets-> Create-> Track menu, you have an option to create new track assets.
  • And finally, you can modify and attach new tracks to the TrackController class by opening the Track scene under the Scenes/Main folder.

Feel free to improve the code and, more importantly, have fun!

Reviewing the level-editor implementation

The implementations in this chapter are simplified versions of the code of a more complex system, but if you take the time to review an advanced version of the level editor in the /FPP folder of the Git project, we will see some improvements, such as the following:

  • Segments: There's an authoring pipeline for segments that uses ScriptableObjects.
  • Object pooling: The TrackController class is using an object pool to optimize the loading time of individual segments.
I didn't include these optimizations in the chapter to keep the code examples short and simple, for educational purposes.

Reviewing alternative solutions

In an actual production context, and if time permits, I would build our game's level editor differently. I would instead design a top-down track editor that would allow the level designers to draw rails and drag and drop obstacles on them. The designers would then be able to save their work in a serialized format.

Then, using spatial-partitioning principles, the tracks would be automatically divided into segments by the TrackController class and put into an object pool. This approach would automate the process of generating individual segments while optimizing the spawning process.

Consequently, the designers would not have to author individual segments as prefabs, and they could design new tracks while visualizing the entire layout in an editor.

When I'm building tools and setting up integration pipelines, my end goal is always automation. I always try to automate myself out of a job so that I don't waste time on manual tasks.

Summary

In this chapter, we took a hands-off approach and reviewed how to build a basic level editor while using the broad ideas of the Spatial Partition pattern. Our goal wasn't to be faithful to standard definitions of the pattern. Instead, we use it as a starting point to build our system. I encourage you to take the time to review the code in the /FPP folder and refactor it to make it better.

In the next chapter, we will review some alternative patterns that are good to know but have general use cases. Therefore, compared to the previous chapters, the use cases will have a broader scope without being specific to a game mechanic or system. The first pattern that we will tackle is the Adapter pattern. As its name implies, we will use it to integrate an adapter between two incompatible systems.

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}