Design Patterns: Object Pooling

Image result for Golf Story

Today’s image is from Golf Story, a Nintendo Switch Game that reminds me a lot of Mario Tennis, one of my favourite GBC games.

This article is going to talk about Object Pooling.  The idea behind Object Pooling is to improve Memory usage by reusing object from a “pool” of a fixed size instead of allocating and freeing them individually. I am going to put this in Unity terms as it is what I do professionally every day and the best way I can explain it.

In Unity you have Instantiate and Destroy methods that are used to Create and Destroy objects. For objects that have quite a long lifespan, these methods don’t cause a massive CPU overhead or at least don’t really interrupt the experience (there are of course various scenarios where this case be the case, but for this example let’s go with this). For objects with a short lifespan, this can cause issues. If you have a lot of objects that are created and destroyed per second then

You're going to have a bad time

The CPU needs to allocate more time to dealing with this creation and destruction. With Unity and also managed languages in general like C#, there is also the magic of Garbage Collection, i.e. a system that deallocates memory that is no longer in use. Depending on what you are working in, Garbage Collection can happen without you really knowing and also in ways under the hood you don’t expect. If you are calling Destroy a lot in Unity you are going to trigger the garbage collector. And triggering the garbage collector likes to slow down CPUs and can cause noticeable slowdowns in gameplay.

Object Pooling can be a way around this. The idea is to create all the objects you’ll need before the gameplay. Instead of actively creating new ones and destroying old ones, the objects get reused from a pool.

To put it another way, you are creating a pool that has a collection of reusable objects inside of it. Instead of creating and destroying these, the objects have a state of whether the game is actively using them or not. Before your gameplay you initialize the pool which creates all the objects you will need up front and sets them to the not being used state. When you need a new object, you ask the pool for one. It finds an available object that is not currently in use and returns it. When the game is finished with the object it is freed up again. Objects can be used without having to create and destroy them all the time.

There is a caveat to this though. You are essentially deciding how many you need of a certain amount of object before you run the game. You could get into one of two scenarios. You may have a smaller pool of objects that save on memory however when you get to your gameplay, you find you have too many. On the other hand, you may assign the number for the pool to create to be more than you will ever need, using more memory.

There is a way to get around this. You can make an object pool that expands if it runs out of objects. If you reach the maximum amount of objects in the pool, the pooling system can create one and add it to the current pool. Although there will be a very small overhead of creating the object, it is better than creating and destroying these object all the time like a maverick.

The thing we haven’t addressed though is when we should use them. Well, object pools are designed for when you need to frequently create and destroy objects that are of a similar size (ideally identical). If you look at a bullet hell game, you don’t want to be creating and destroying all those bullets all the time as it will most likely kill your performance. Similarly with particle systems. That continuous smoke cloud coming out of your Volcano will want to use pooling.

Essentially, that is a brief overview of Object Pooling. If you are creating and destroying lots of similar objects in your game, then Object Pooling is for you!

Design Patterns: The Strategy Pattern

Have you guys played Pyre yet? No? Well do. It is one of my favourite games this year. It is also a sort of Strategy game… kind of… it is hard to define what it is really, but it has strategy elements!

In this post I am going to talk about the Strategy pattern. In wikipedia term, the Strategy pattern is a behavioural software design pattern that enables an algorithm’s behaviour to be selected at runtime. Fancy.

In game development terms, we could look at enemies. In an action game, maybe you want the enemies to have different behaviours when they fight the player. I am going to use like an Ace Combat style game as an example. Each Enemy Pilot has some standard stuff, but we want the pilot AI to do many different things. We could use the strategy pattern for this.

public class EnemyPilot
{
    .. Other code here
    private IPilotAI _pilotAI;
    void Update()
    {
         _pilotAI.Update();
    }
}

In the above C# code, I have a class that is the EnemyPilot that contains the IPilotAI interface that we can set at runtime. We can now make a number of AI behaviours that use the Pilot AI interface. This is much better than inheriting from the whole EnemyPilot class each time and we are encapsulating the only thing that varies, i.e. the Pilot AI. And really it as that. Cool huh?

Design Patterns – Observer

Today I am going to talk about the Observer Pattern. From Wikipedia once again:

“The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.”

In plain old English, the Observer pattern “Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified.”

What does this amount to in the real world. So you know when you sign up to one of those voucher code sites for a specifc type of voucher and you get a notification whenever there is a new voucher type available? That is basically the observer pattern.

In game development a common use case is an Achievement system. It is an example that has been used multiple times, but hey, if it ain’t broke, don’t fix it. In a game, there are Achievements that can be obtained through a variety of different methods. Maybe you are working on Final Fantasy 12 and want to add an achievement that the player gets for shouting they are Captain Basch 1000 times.

If we aren’t clever about how we design this system, we could have a crazy spaghetti like thing that is linked to every part of our code base. This is bad, as the likely hood of you breakign the achievement system if you make a change or vice versa is pretty high. Are you thinking about using a Singleton for this? DON’T. This is a prime example of where not to use a Singleton. We want our nice Achievement system all lumped in one place and we don’t want to tightly couple the system to every single part of the code base. This is where the Observer pattern comes in. The pattern allows one piece of code to announce something has happenned without actually giving a damn who recieves the notification.

Let’s look at some nice C# code. Essentilaly the code can be broken down into two parts. The Subject  and the Observer.

First we will take a look at the subject. The subject holds a list of all the observers interested in getting information ewhen something cool happens. When said something has happenned, it sends a notificaiton to all the observers.

public abstract class Subject
{
    List<IObserver> _observers = new List<Observers>();
    
    public void Notify()
    {
        _observers.ForEach(x => x.OnNotify());
    }

    public void AddObserver(Observer observer)
    {
        _observers.Add(observer);
    }
    public void RemoveObserver(Observer observer)
    {
        _observer.Remove(observer);
    }
}

And to reiterate somewhat, the Observers are the objects interested in doing something when the event happens.

public interface IObserver
{
    void OnNotify();
}

In fact rather than going into the previously mentioned Achievement system, I am going to talk about the “I’m Captian Basch” bit in FF12.

What I want is the NPCs in a certain area to see if they hear it and increase the notoriety. In the below code I have already added the NPCs as Observers from some other system.

public class BaschShouter : Subject
{
...
    private void OnShoutedImBasch()
    { 
        Notify();
    }
...
}

So every time the player refutes Ondore’s lies:

public class NPC : IObserver
{
     public void OnNotify()
     {
          if (NPCIsInEarShotOfPlayer())
          {
              DontBelieveOndoresLies();
          }
     }
}

You also may have some NPCs that are loyal and stop you shouting and you have also registered those:

public class NPCLoyalToOndore : IObserver 
{ 
    public void OnNotify() 
    { 
       if (NPCIsInEarShotOfPlayer())
       {
            ChastisePlayerForLyingAboutMyLeige();
       }
    } 
}

And there we have it. Observer pattern.