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.
Code
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);
}
}
}
}using UnityEngine;
namespace Patterns.Structural.Flyweight
{
/// <summary>
/// The flyweight: everything trees of one species have in common.
/// One asset is shared by every oak in the forest, whether 10 or 10,000.
/// </summary>
[CreateAssetMenu(menuName = "Forest/Tree Model")]
public class TreeModel : ScriptableObject
{
[Header("Intrinsic state (shared, read-only at runtime)")]
[SerializeField] private Mesh mesh;
[SerializeField] private Material material; // shader with "Enable GPU Instancing"
[SerializeField] private float windStrength = 0.4f;
[SerializeField] private int woodYield = 12;
public Mesh Mesh => mesh;
public Material Material => material;
public float WindStrength => windStrength;
public int WoodYield => woodYield;
}
}using UnityEngine;
namespace Patterns.Structural.Flyweight
{
/// <summary>
/// Extrinsic state: the few values that really differ per tree.
/// A plain struct, so 10,000 of them sit in one contiguous array.
/// (Inside this namespace it shadows UnityEngine.TreeInstance, the terrain type.)
/// </summary>
[System.Serializable]
public struct TreeInstance
{
public Vector3 Position;
public float Scale;
public float Yaw;
public Color Tint;
public Matrix4x4 ToMatrix() =>
Matrix4x4.TRS(Position, Quaternion.Euler(0f, Yaw, 0f), Vector3.one * Scale);
}
}using UnityEngine;
namespace Patterns.Structural.Flyweight
{
/// <summary>
/// Unity's own flyweight trap: reading renderer.material silently clones
/// the shared material for this renderer. A MaterialPropertyBlock keeps
/// the material shared and stores only the per-object override.
/// </summary>
public class TintedRenderer : MonoBehaviour
{
private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
[SerializeField] private Renderer target;
[SerializeField] private Color tint = Color.green;
private void Start()
{
// BAD: allocates a Material copy that you now own and must Destroy.
// target.material.color = tint;
// ALSO BAD: changes the asset for EVERY renderer that uses it.
// target.sharedMaterial.color = tint;
// GOOD: shared material, per-renderer value.
var block = new MaterialPropertyBlock();
target.GetPropertyBlock(block);
block.SetColor(BaseColorId, tint);
target.SetPropertyBlock(block);
}
}
}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 modelreference, shared by every tree of that kind. ChopandSwayreadmodel.WoodYieldandmodel.WindStrengthinstead of per-tree copies.- The tint is applied with a
MaterialPropertyBlockandsharedMaterial, so no material is cloned. - Only
tintstays on the tree: it is the one piece of truly extrinsic state.
using UnityEngine;
namespace Patterns.Structural.Flyweight
{
/// <summary>
/// Without Flyweight: every tree GameObject carries its own copy of the
/// species data and clones its material to apply a tint.
/// </summary>
public class ForestTree : MonoBehaviour
{
// Duplicated on all 5,000 oaks, and tuned one prefab override at a time.
[SerializeField] private string speciesName = "Oak";
[SerializeField] private float windStrength = 0.4f;
[SerializeField] private int woodYield = 12;
[SerializeField] private AnimationCurve growthCurve;
// Genuinely per-tree.
[SerializeField] private Color tint = Color.white;
private void Start()
{
var meshRenderer = GetComponent<MeshRenderer>();
// Reading .material clones the material: one copy per tree.
meshRenderer.material.color = tint;
}
public int Chop() => woodYield;
public float Sway(float time) => Mathf.Sin(time) * windStrength;
}
}using UnityEngine;
namespace Patterns.Structural.Flyweight
{
/// <summary>
/// With Flyweight: species data lives once in a shared TreeModel asset;
/// the tree keeps only what is unique to it.
/// </summary>
public class ForestTree : MonoBehaviour
{
private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
// Shared by every oak: one asset, tuned in one place.
[SerializeField] private TreeModel model;
// Genuinely per-tree.
[SerializeField] private Color tint = Color.white;
private void Start()
{
var meshRenderer = GetComponent<MeshRenderer>();
// Keep the shared material; override the tint per renderer instead.
meshRenderer.sharedMaterial = model.Material;
var block = new MaterialPropertyBlock();
block.SetColor(BaseColorId, tint);
meshRenderer.SetPropertyBlock(block);
}
public int Chop() => model.WoodYield;
public float Sway(float time) => Mathf.Sin(time) * model.WindStrength;
}
}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.materialclones the material for that renderer.
Tips
- 01Use
renderer.sharedMaterialto read the shared material, and aMaterialPropertyBlockfor per-object colours. Accessingrenderer.materialallocates a copy you must alsoDestroyyourself. - 02Enable GPU Instancing on the material, and draw large static sets with
Graphics.RenderMeshInstancedinstead of one GameObject per object. - 03Put the intrinsic data in a
ScriptableObjectso designers can tune one asset and see every instance update. - 04Keep instance data in structs and arrays rather than classes, so thousands of instances stay compact in memory.
- 05Check the Memory Profiler for many
Material (Instance)entries; it is the most common sign of a broken flyweight.