Flyweight in Unity (Design Pattern)

Marcus Ansley
2 min readJul 2, 2021

--

Essentially, the flyweight design pattern minimises memory use by sharing as much data as possible with similar objects. We would typically use something like this in Unity when we have many, many repeated instances of a class (‘objects’) each with similar, if not identical, variables and values. Using the example that was taught to me (as part of a GameDevHQ course), let’s take a look at this Enemy class:

We could probably instantiate ten or twenty or even a hundred or so of these enemies and realistically not notice much of a difference in terms of performance. But in each instance of this class we’ll be allocating memory to, at the very least, all three of these class-level variables (_currentHealth, _maxHealth, and _speed). This can get a bit overwhelming when we have say, 10,000 enemies all in the scene at the same time, and would most likely crash the game for most computers. The flyweight design pattern seeks to address or at least alleviate some of this by using static variables (i.e. variables which will be the same in every instance of this class). So in this case, while the _currentHealth variable will most likely change for each instance of the Enemy class, the _maxHealth and _speed variables are likely to be consistent across all instances. As such, rather than creating object-specific variables, we can essentially make this class-specific instead:

Something like this can quickly and easily reduce the amount of memory instances of our classes are taking up 😉

--

--

Marcus Ansley
Marcus Ansley

Written by Marcus Ansley

Game Developer | Game Design and Literature Graduate

Responses (1)