Flyweight - extra pattern for game developers

Hi guys!

First and foremost, great and clear examples in this course! I have watched a couple of videos on youtube for game programming patterns and most weren’t as clear as these :slight_smile:

One I have come across recently, and I think would be a great addition to this list, is the Flyweight pattern.
Seeing as I am still learning to program myself I’ll do my best to explain this one for beginners. I suggest watching some videos and/or reading about this as well.
Flyweight (great one)

The Flyweight pattern is used to minimize the amount of memory used by sharing common parts between multiple object, instead of each object having to keep all of that data for itself. I know, not the best way to explain… so here is an example I found easy to understand!

Take a tree in a game for example. You might be making a 2D game where there are thousands of 2D trees in there! Each of these containing all data needed for a tree. What the Flyweight pattern actually does is seperate the data that ALL trees (repeating / intrinsic data) have from the data that each seperate tree has (unique / extrinsic data).

In the case of trees, it would maybe look a bit like this:
Repeating / intrinsic

  • The tree Sprite itself
  • The color

Unique / extrinsic

  • Position in world
  • Size

The Flyweight pattern stores the above (repeating) data in a seperate object and distributes this to the object that need this, thus minimizing the data each seperate object caries with it! This could potentially decrease your memory usage by a very large amount :smiley:

I suggest reading the article via the link above. Like I mentioned, I am also new and just started learning all these patterns, but this one caught my attention as I was thinking about something like this myself just before I came across this.

Please feel free to correct me or add to this anything I have forgotten :slight_smile:!

1 Like

Good find, Xavvey!

To see the Flyweight Pattern in action, all one has to do is look to Unity itself.

The prefab contains Gameobject data, and often contains things like Mesh Renderers… those Mesh renderers hold a link to a Mesh, which many many other Gameobjects may also have in common. Unless deformation is involved (characters), ONE copy of the Mesh is sent to the Graphics card, with calls to the specific shaders being used by that prefab.

When you put a prefab in the scene, if there are no changes, the only data stored is a link to the prefab, and then any overrides or additional components you may have.

It’s one of those patterns that is, in itself, intrinsic to Unity without our ever having to do a thing (besides using Prefabs whenever possible, and sharing meshes and other linkable components whenever possible).

2 Likes

Privacy & Terms