چیست؟
Type Object هر موجودیت بازی را دو تکه میکند: instance (همین گابلین مشخص، با سلامتی فعلی و موقعیت خودش) و type آن (چیزهایی که همهٔ گابلینها مشترک دارند: حداکثر سلامتی، سرعت، قدرت حمله، رنگ و prefab). instance یک ارجاع به type خودش نگه میدارد و مقدارهای مشترک را از طریق آن میخواند.
در Unity این type تقریباً همیشه یک ScriptableObject است. یک asset از نوع EnemyType به اسم Orc عددها را نگه میدارد و فقط یک MonoBehaviour ساده به اسم Enemy همهٔ نوعهای دشمن را اداره میکند. ساختن یک هیولای تازه یعنی Create → Patterns → Enemy Type، نه یک فایل C# جدید و یک بار کامپایل دیگر.
چون صدها instance به همان asset اشاره میکنند، تغییر آن asset همهشان را با هم عوض میکند. اگر در Play Mode مقدار Orc.speed را در Inspector بالا ببری، همهٔ اورکهای روی صفحه از فریم بعد تندتر میشوند، چون Enemy.Update بهجای یک کپی، خود type.Speed را میخواند.
کِی به کار میآید؟
وقتی «نوع»های زیادی از یک چیز داری که بیشتر در داده با هم فرق دارند، سراغش برو: دشمنها، سلاحها، آیتمها، طلسمها، tileها، نوع محصولات کشاورزی و تعریف کارتها.
از همان لحظهای که طراحها باید بدون انتظار برای برنامهنویس نوع تازه اضافه کنند یا بالانس را عوض کنند، ارزشش را نشان میدهد. یک importer از روی spreadsheet یا یک pipeline برای mod هم میتواند در زمان اجرا type بسازد، چون type فقط داده است.
اگر نوعها واقعاً در رفتار فرق دارند، نه در عدد، از آن استفاده نکن. یک باس با نبرد سهمرحلهای منحصربهفرد یک ردیف در جدول نیست؛ برایش کد بنویس (یا برای بخش رفتار، Type Object را با Strategy یا Subclass Sandbox ترکیب کن).
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using System.Collections.Generic;
using UnityEngine;
namespace Patterns.GameProgramming.TypeObject
{
/// <summary>
/// Spawns enemies from a list of EnemyType assets. Adding a new kind of
/// enemy means dragging one more asset into this list, not writing a class.
/// </summary>
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private List<EnemyType> types = new();
[SerializeField] private float radius = 6f;
private readonly List<Enemy> alive = new();
private void Update()
{
// Keys 1..9 spawn the matching type from the list.
for (int i = 0; i < types.Count && i < 9; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
SpawnOne(types[i]);
}
if (Input.GetKeyDown(KeyCode.L))
LogCounts();
}
private void SpawnOne(EnemyType type)
{
Vector2 offset = Random.insideUnitCircle * radius;
Vector3 position = transform.position + new Vector3(offset.x, 0f, offset.y);
alive.Add(type.Spawn(position, Quaternion.identity));
}
private void LogCounts()
{
alive.RemoveAll(e => e == null);
foreach (EnemyType type in types)
{
int count = alive.FindAll(e => e.Type == type).Count;
Debug.Log($"{type.DisplayName}: {count} alive, speed {type.Speed}");
}
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.TypeObject
{
/// <summary>
/// The Type Object. One asset per kind of enemy ("Goblin", "Orc", ...).
/// Designers create new kinds in the Project window; no new class is needed.
/// </summary>
[CreateAssetMenu(menuName = "Patterns/Enemy Type", fileName = "NewEnemyType")]
public class EnemyType : ScriptableObject
{
[SerializeField] private string displayName = "Goblin";
[SerializeField, Min(1)] private int maxHealth = 30;
[SerializeField, Min(0f)] private float speed = 3f;
[SerializeField, Min(0)] private int attack = 5;
[SerializeField] private Enemy prefab;
[SerializeField] private Color color = Color.green;
public string DisplayName => displayName;
public int MaxHealth => maxHealth;
public float Speed => speed;
public int Attack => attack;
public Color Color => color;
/// <summary>The "constructor" of the kind: every instance is born here.</summary>
public Enemy Spawn(Vector3 position, Quaternion rotation)
{
Enemy enemy = Instantiate(prefab, position, rotation);
enemy.Init(this);
return enemy;
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.TypeObject
{
/// <summary>
/// One class for every kind of enemy. Shared data lives in the EnemyType;
/// only per-instance state (current health, target) lives here.
/// </summary>
[RequireComponent(typeof(Renderer))]
public class Enemy : MonoBehaviour
{
private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
[SerializeField] private EnemyType type;
[SerializeField] private Transform target;
private int currentHealth;
private MaterialPropertyBlock block;
public EnemyType Type => type;
public int CurrentHealth => currentHealth;
public void Init(EnemyType enemyType)
{
type = enemyType;
currentHealth = type.MaxHealth;
name = type.DisplayName;
block ??= new MaterialPropertyBlock();
block.SetColor(BaseColorId, type.Color);
GetComponent<Renderer>().SetPropertyBlock(block);
}
private void Start()
{
// Enemies placed in a scene by hand still get initialised.
if (currentHealth == 0 && type != null) Init(type);
}
private void Update()
{
if (target == null) return;
// Read through the type every frame, so a designer tweak
// to the asset changes every Orc in the scene at once.
transform.position = Vector3.MoveTowards(
transform.position, target.position, type.Speed * Time.deltaTime);
}
public int RollAttack() => type.Attack;
public void TakeDamage(int amount)
{
currentHealth = Mathf.Max(0, currentHealth - amount);
if (currentHealth == 0) Destroy(gameObject);
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: یک subclass برای هر دشمن با آمار hard-codeشده. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
Goblin، Orc و Troll هر کدام از Enemy ارث میبرند فقط برای اینکه از MaxHealth، Speed و Attack عددهای متفاوتی برگردانند. در رفتار هیچ فرق واقعیای با هم ندارند.
هر دور بالانس یعنی تغییر کد و یک domain reload. طراحها بدون برنامهنویس نمیتوانند یک «Skeleton» اضافه کنند، و بیست نوع دشمن یعنی بیست کلاس تقریباً یکسان و بیست prefab که هر کدام باید به اسکریپت درست وصل شوند.
✓ چه چیزی عوض شد؟
- سه subclass حذف شدند؛
Enemyدیگرabstractنیست. - یک ScriptableObject تازه به اسم
EnemyTypeفیلدهای serializeشدهٔmaxHealth،speedوattackرا نگه میدارد، وEnemyیک ارجاع[SerializeField] private EnemyType typeگرفته است. - propertyهای abstract حالا یکخطیهایی مثل
Speed => type.Speedهستند؛ پسUpdateوTakeDamageدست نخوردهاند. - Goblin، Orc و Troll حالا asset هستند؛ پس تنظیم یا اضافه کردن یک نوع در Inspector انجام میشود، حتی در Play Mode.
using UnityEngine;
namespace Patterns.GameProgramming.TypeObject
{
/// <summary>
/// Without Type Object: every kind of enemy is its own subclass
/// with its stats hard-coded in C#.
/// </summary>
public abstract class Enemy : MonoBehaviour
{
[SerializeField] protected Transform target;
protected int currentHealth;
protected abstract int MaxHealth { get; }
protected abstract float Speed { get; }
public abstract int Attack { get; }
private void Awake() => currentHealth = MaxHealth;
private void Update()
{
if (target == null) return;
transform.position = Vector3.MoveTowards(
transform.position, target.position, Speed * Time.deltaTime);
}
public void TakeDamage(int amount)
{
currentHealth = Mathf.Max(0, currentHealth - amount);
if (currentHealth == 0) Destroy(gameObject);
}
}
// Faster Orcs? Ask a programmer, edit a number, wait for a recompile.
public class Goblin : Enemy
{
protected override int MaxHealth => 30;
protected override float Speed => 4f;
public override int Attack => 4;
}
public class Orc : Enemy
{
protected override int MaxHealth => 80;
protected override float Speed => 2.5f;
public override int Attack => 10;
}
public class Troll : Enemy
{
protected override int MaxHealth => 200;
protected override float Speed => 1.2f;
public override int Attack => 18;
}
}using UnityEngine;
namespace Patterns.GameProgramming.TypeObject
{
/// <summary>
/// With Type Object: one Enemy class. Goblin, Orc and Troll are now
/// EnemyType assets that designers create and tune in the Inspector.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] protected Transform target;
[SerializeField] private EnemyType type;
protected int currentHealth;
protected int MaxHealth => type.MaxHealth;
protected float Speed => type.Speed;
public int Attack => type.Attack;
private void Awake() => currentHealth = MaxHealth;
private void Update()
{
if (target == null) return;
transform.position = Vector3.MoveTowards(
transform.position, target.position, Speed * Time.deltaTime);
}
public void TakeDamage(int amount)
{
currentHealth = Mathf.Max(0, currentHealth - amount);
if (currentHealth == 0) Destroy(gameObject);
}
}
// Goblin.asset, Orc.asset, Troll.asset: tuned live, no recompile.
[CreateAssetMenu(menuName = "Patterns/Enemy Type")]
public class EnemyType : ScriptableObject
{
[SerializeField, Min(1)] private int maxHealth = 30;
[SerializeField, Min(0f)] private float speed = 3f;
[SerializeField, Min(0)] private int attack = 5;
public int MaxHealth => maxHealth;
public float Speed => speed;
public int Attack => attack;
}
}مزایا و معایب
+ مزایا
- نوعهای تازه هیچ کدی و هیچ کامپایلی لازم ندارند؛ محتوا دست طراحهاست.
- دادهٔ مشترک برای هر type یک بار ذخیره میشود، نه برای هر instance؛ پس وقتی تعداد instanceها زیاد است، در حافظه صرفهجویی میشود.
- تنظیم زنده: یک تغییر در asset همهٔ instanceهایی را که به آن ارجاع دارند بهروز میکند.
− معایب
- تنوع دادن به رفتار سختتر از تنوع دادن به داده است؛ آخرش برای بیان تفاوتها flag یا فیلدهای strategy به type اضافه میکنی.
- تغییرهایی که در Play Mode روی یک
ScriptableObjectمیدهی در Editor باقی میمانند؛ اولین باری که یک تغییر آزمایشی سر از build درمیآورد، همه غافلگیر میشوند. - بهجای یک شیء دو شیء داری؛ باید فیلدهای «مخصوص type» و «مخصوص instance» را واضح از هم جدا نگه داری، وگرنه state مربوط به instance به asset مشترک نشت میکند.
چند نکتهٔ کاربردی
- ۰۱هیچوقت state مخصوص instance (مثل
currentHealth) را در asset مربوط به type ننویس. همهٔ instanceها آن را شریک میشوند و در Editor هم روی دیسک ذخیره میشود. - ۰۲مقدارهای type را از طریق ارجاع بخوان (
type.Speed) و آنها را درAwakecache نکن، مگر اینکه عمداً بخواهی instanceها تغییرهای بعدی را نادیده بگیرند. - ۰۳به type یک متد factory مثل
EnemyType.Spawnبده تا ساختن هر instance همیشه از مسیر نوع خودش بگذرد وInitهیچوقت یادت نرود. - ۰۴برای ارثبری بین typeها (یک «Elite Orc» که فقط سرعت را عوض میکند)، یک فیلد اختیاری
parentاضافه کن و برای مقدارهای تنظیمنشده سراغ آن برو. - ۰۵این همان Flyweight با تمرکز روی گیمپلی است: Flyweight دربارهٔ اشتراک حافظه است و Type Object دربارهٔ اینکه داده نوعها را تعریف کند.