چیست؟
Flyweight دادهٔ یک شیء را دو قسمت میکند. state ذاتی (intrinsic) برای همهٔ اشیای یک نوع یکسان است: mesh، material، texture و تنظیمات باد یک درخت. state بیرونی (extrinsic) همان چیزی است که هر کدام را منحصربهفرد میکند: موقعیت، اندازه، چرخش و رنگش. قسمت ذاتی یک بار ذخیره و بین همه تقسیم میشود؛ هر instance فقط قسمت بیرونی را نگه میدارد.
در Unity قسمت مشترک معمولاً یک ScriptableObject یا یک کلاس ساده مثل TreeModel است و قسمت مخصوص هر instance یک struct کوچک مثل TreeInstance. آن وقت جنگلی با ۱۰٬۰۰۰ درخت بلوط فقط یک mesh و یک material بهاضافهٔ ۱۰٬۰۰۰ struct کوچک خرج دارد، نه ۱۰٬۰۰۰ کپی کامل.
GPU instancing همین ایده در سمت رندر است. Graphics.RenderMeshInstanced یک mesh، یک material و یک آرایه از ماتریسها میگیرد و همه را با چند draw call محدود میکشد. درختها و چمن terrain در Unity و سیستمهای ذره، همه پشت صحنه همینطور کار میکنند.
کِی به کار میآید؟
وقتی تعداد زیادی شیء داری که بیشتر دادهشان مشترک است سراغش برو: درخت، سنگ، چمن، گلوله، tile، آدمهای یک جمعیت، آیتمهای همنوع در inventory.
بیشترین اثر را وقتی دارد که دادهٔ مشترک بزرگ است (mesh، texture، curve، فهرست طولانی statها) و تعداد هم زیاد است. اینجاست که حافظه و draw callها واقعاً روی هم جمع میشوند.
اگر هر شیء واقعاً منحصربهفرد است، یا فقط چند ده شیء داری، این تقسیم فقط یک لایهٔ غیرمستقیم اضافه میکند و صرفهجویی معناداری ندارد.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
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);
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: هزاران درخت که هر کدام دادهٔ گونه و material خودشان را کپی میکنند. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
هر prefab درخت یک ForestTree دارد با speciesName، windStrength، woodYield و growthCurve مخصوص خودش. در Start هم برای رنگ دادن، meshRenderer.material.color را تنظیم میکند.
با ۵٬۰۰۰ درخت یعنی ۵٬۰۰۰ کپی از همان تنظیمات، و تنظیم دوبارهٔ باد یعنی ویرایش prefab و امید به اینکه هیچ instanceی override نداشته باشد. بدتر اینکه خواندن .material برای هر درخت یک کپی از material میسازد؛ پس Memory Profiler ۵٬۰۰۰ شیء Material (Instance) نشان میدهد و batching هم میشکند.
✓ چه چیزی عوض شد؟
- چهار فیلد مربوط به گونه جایشان را به یک ارجاع
TreeModel modelدادهاند که بین همهٔ درختهای آن نوع مشترک است. ChopوSwayبهجای کپیهای مخصوص هر درخت،model.WoodYieldوmodel.WindStrengthرا میخوانند.- رنگ با
MaterialPropertyBlockوsharedMaterialاعمال میشود، پس هیچ materialی کپی نمیشود. - فقط
tintروی درخت مانده است: تنها 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;
}
}مزایا و معایب
+ مزایا
- حافظه از تعداد × شیء کامل به یک مدل مشترک + تعداد × instance کوچک پایین میآید.
- با تنظیم مدل مشترک، همهٔ instanceها یکجا و از یک نقطه عوض میشوند.
- دادهٔ کوچک و یکدست هر instance برای GPU instancing، Jobs و Burst ایدهآل است.
− معایب
- با state مشترک باید فقطخواندنی رفتار کنی؛ اگر یک instance آن را عوض کند، همه عوض میشوند.
- منطقی که به هر دو قسمت نیاز دارد باید state بیرونی را بهعنوان ورودی بگیرد و این بعضی کدها را کمی غیرمستقیمتر میکند.
- APIهای Unity ممکن است بیسروصدا اشتراک را بشکنند: خواندن
renderer.materialبرای آن renderer یک کپی از material میسازد.
چند نکتهٔ کاربردی
- ۰۱برای خواندن material مشترک از
renderer.sharedMaterialاستفاده کن و برای رنگ مخصوص هر شیء ازMaterialPropertyBlock. دسترسی بهrenderer.materialیک کپی میسازد که باید خودتDestroyاش هم بکنی. - ۰۲روی material گزینهٔ GPU Instancing را روشن کن و مجموعههای بزرگ ثابت را بهجای یک GameObject برای هر شیء، با
Graphics.RenderMeshInstancedبکش. - ۰۳دادهٔ ذاتی را در یک
ScriptableObjectبگذار تا طراحها یک asset را تنظیم کنند و بهروز شدن همهٔ instanceها را ببینند. - ۰۴دادهٔ instanceها را بهجای کلاس در struct و آرایه نگه دار تا هزاران instance در حافظه فشرده بمانند.
- ۰۵در Memory Profiler دنبال تعداد زیادی
Material (Instance)بگرد؛ این رایجترین نشانهٔ یک flyweight شکسته است.