Game Design Pattern (Part 5/5): Flyweight

Simon Pham
2 min readApr 28, 2024

In today’s blog post of the game design pattern series, let’s talk about another pattern called Flyweight.

What is a Flyweight Pattern?

The Flyweight pattern is a design pattern used to optimize memory usage and performance by sharing common state or data between multiple objects. This pattern is particularly useful when dealing with a large number of similar objects that share certain properties.

How do I implement the Observer Pattern?

Let’s look at this script that I have for the enemy.

using UnityEngine;

public class Enemy: MonoBehaviour
{
private int _maxHealth = 200;
private int _currentHealth;
private float _speed = 5f;
private float _attackStat = 10;
private float _defenseStat = 10;
private int _shieldAmount = 15;

private void Start(){
_currentHealth = _maxHealth;
}
}

So for each enemy spawned, an instance of this script will be created and if you have like dozens of this enemy type, it wouldn’t be an issue but if you have a Spawn Manager that spawns thousands of this enemy, you’d need to implement the Flyweight pattern to optimize your game.

This enemy has 6 unique properties, and if we have a thousand enemies, we’d have a thousand copies of those properties that would be occupying the memory. If you take a closer look, the only difference between these enemy instances is their current health amount because they would all have the same maximum health, speed, attack and defense stat, and shield amount. So to optimize our game, we can turn those properties into static properties which means that they will be shared between those instances.

using UnityEngine;

public class Enemy: MonoBehaviour
{
private static int _maxHealth = 200;
private int _currentHealth;
private static float _speed = 5f;
private static float _attackStat = 10;
private static float _defenseStat = 10;
private static int _shieldAmount = 15;

private void Start(){
_currentHealth = _maxHealth;
}
}

Another way to optimize the engine’s memory is to use scriptable objects. A scriptable object is a smart data container that can be shared among the enemies, and we will have a separate article about scriptable objects.

--

--