←All patterns
Structural

Flyweight

Share the heavy data that many objects have in common, and keep only the small per-object differences on each instance.

What Is It?

Flyweight splits an object’s data into two parts. Intrinsic state is the same for every object of a kind: a tree’s mesh, material, texture and wind settings. Extrinsic state is what makes each one unique: its position, scale, rotation and tint. The intrinsic part is stored once and shared; each instance keeps only the extrinsic part.

In Unity the shared part is usually a ScriptableObject or a plain class such as TreeModel, and the per-instance part is a small struct such as TreeInstance. A forest of 10,000 oaks then costs one mesh and one material plus 10,000 tiny structs, instead of 10,000 full copies.

GPU instancing is the same idea on the rendering side. Graphics.RenderMeshInstanced takes one mesh, one material and an array of matrices, and draws all of them in a handful of draw calls. Unity terrain trees, grass and particle systems all work this way under the hood.

When Is It Used?

Use it when you have many objects that share most of their data: trees, rocks, grass, bullets, tiles, crowd members, inventory items of the same kind.

It matters most when the shared data is large (meshes, textures, curves, long lists of stats) and the count is high. That is where memory and draw calls really add up.

If each object is truly unique, or you only have a few dozen of them, the split adds indirection without a meaningful saving.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Flyweight Pattern
trees8memory53.7 MBdraw calls8material clones0
Oak.asset
unused
Mesh
Texture
Material
6.71 MB ×1
each tree owns a copy53.7 MB
shared model + instances6.71 MB
Per tree: 6.71 MB copied vs 36 bytes of TreeInstance
Console
Press a button to see what happens…

Code

Assets / Scripts / Structural/ Flyweight ›Forest.cs
using UnityEngine;

namespace Patterns.Structural.Flyweight
{
    /// <summary>
    /// Draws every tree of one model with GPU instancing: one mesh, one
    /// material, plus a matrix and a tint per instance. No GameObject per tree.
    /// </summary>
    public class Forest : MonoBehaviour
    {
        private const int BatchSize = 1023;
        private static readonly int TintId = Shader.PropertyToID("_Tint");

        [SerializeField] private TreeModel model;
        [SerializeField] private TreeInstance[] trees;

        private readonly Matrix4x4[] matrices = new Matrix4x4[BatchSize];
        private readonly Vector4[] tints = new Vector4[BatchSize];
        private MaterialPropertyBlock block;

        private void Awake() => block = new MaterialPropertyBlock();

        private void Update()
        {
            var rp = new RenderParams(model.Material) { matProps = block };

            for (int start = 0; start < trees.Length; start += BatchSize)
            {
                int count = Mathf.Min(BatchSize, trees.Length - start);
                for (int i = 0; i < count; i++)
                {
                    matrices[i] = trees[start + i].ToMatrix();
                    tints[i] = trees[start + i].Tint;
                }

                // _Tint must be an instanced property in the shader.
                block.SetVectorArray(TintId, tints);
                Graphics.RenderMeshInstanced(rp, model.Mesh, 0, matrices, count);
            }
        }
    }
}
4 files · namespace Patterns.Structural.FlyweightC# · UTF-8 · LF

Before & After

Real-world smell: thousands of trees that each copy their species data and material. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Every tree prefab has a ForestTree with its own speciesName, windStrength, woodYield and growthCurve. In Start it sets meshRenderer.material.color to apply a tint.

With 5,000 trees that is 5,000 copies of the same settings, and retuning the wind means editing a prefab and hoping no instance has an override. Worse, reading .material clones the material for every tree, so the Memory Profiler shows 5,000 Material (Instance) objects and batching breaks.

✓ What changed

  • The four species fields are replaced by one TreeModel model reference, shared by every tree of that kind.
  • Chop and Sway read model.WoodYield and model.WindStrength instead of per-tree copies.
  • The tint is applied with a MaterialPropertyBlock and sharedMaterial, so no material is cloned.
  • Only tint stays on the tree: it is the one piece of truly extrinsic state.
ForestTree.Before.cs → ForestTree.After.cs+13/−11
11 using UnityEngine;
22
33 namespace Patterns.Structural.Flyweight
44 {
55 /// <summary>
6− /// Without Flyweight: every tree GameObject carries its own copy of the
7− /// species data and clones its material to apply a tint.
6+ /// With Flyweight: species data lives once in a shared TreeModel asset;
7+ /// the tree keeps only what is unique to it.
88 /// </summary>
99 public class ForestTree : MonoBehaviour
1010 {
11− // Duplicated on all 5,000 oaks, and tuned one prefab override at a time.
12− [SerializeField] private string speciesName = "Oak";
13− [SerializeField] private float windStrength = 0.4f;
14− [SerializeField] private int woodYield = 12;
15− [SerializeField] private AnimationCurve growthCurve;
11+ private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
1612
13+ // Shared by every oak: one asset, tuned in one place.
14+ [SerializeField] private TreeModel model;
15+
1716 // Genuinely per-tree.
1817 [SerializeField] private Color tint = Color.white;
1918
2019 private void Start()
2120 {
2221 var meshRenderer = GetComponent<MeshRenderer>();
2322
24− // Reading .material clones the material: one copy per tree.
25− meshRenderer.material.color = tint;
23+ // Keep the shared material; override the tint per renderer instead.
24+ meshRenderer.sharedMaterial = model.Material;
25+ var block = new MaterialPropertyBlock();
26+ block.SetColor(BaseColorId, tint);
27+ meshRenderer.SetPropertyBlock(block);
2628 }
2729
28− public int Chop() => woodYield;
30+ public int Chop() => model.WoodYield;
2931
30− public float Sway(float time) => Mathf.Sin(time) * windStrength;
32+ public float Sway(float time) => Mathf.Sin(time) * model.WindStrength;
3133 }
3234 }

Advantages & Disadvantages

+ Advantages

  • Memory drops from count × full object to one shared model + count × small instance.
  • Tuning the shared model changes every instance at once, from a single place.
  • Small, uniform instance data is ideal for GPU instancing, Jobs and Burst.

− Disadvantages

  • Shared state must be treated as read-only; one instance changing it changes all of them.
  • Logic that needs both parts has to pass the extrinsic state in, which makes some code a little less direct.
  • Unity APIs can quietly break the sharing: reading renderer.material clones the material for that renderer.

Tips

  1. 01Use renderer.sharedMaterial to read the shared material, and a MaterialPropertyBlock for per-object colours. Accessing renderer.material allocates a copy you must also Destroy yourself.
  2. 02Enable GPU Instancing on the material, and draw large static sets with Graphics.RenderMeshInstanced instead of one GameObject per object.
  3. 03Put the intrinsic data in a ScriptableObject so designers can tune one asset and see every instance update.
  4. 04Keep instance data in structs and arrays rather than classes, so thousands of instances stay compact in memory.
  5. 05Check the Memory Profiler for many Material (Instance) entries; it is the most common sign of a broken flyweight.