چیست؟
مدلسازی دشمنها با وراثت بیخطر شروع میشود: Enemy، بعد FlyingEnemy : Enemy، بعد ShootingFlyingEnemy : FlyingEnemy. بعد تیم طراحی یک دشمن پیادهٔ تیرانداز، یک پرندهٔ درمانگر و یک برجک میخواهد که شلیک میکند ولی هیچوقت حرکت نمیکند. هر ترکیب تازه یک کلاس تازه میخواهد، کد مشترک به بالا، به یک کلاس پایهٔ پفکرده، هل داده میشود و درخت بهصورت ترکیبیاتی رشد میکند: پنج توانایی مستقل میتوانند ۳۱ نوع موجودیت مختلف بسازند.
پترن Component این را برعکس میکند. یک موجودیت فقط یک ظرف است و هر توانایی یک شیء کوچک است که یک کار انجام میدهد: Health جان را نگه میدارد، Mover حرکت میدهد، Shooter شلیک میکند و EnemyBrain تصمیم میگیرد. برای یک تیرانداز پرنده، یک Mover پرنده و یک Shooter را میچسبانی؛ هیچ کلاس تازهای نوشته نمیشود. پنج توانایی یعنی پنج component، هر ترکیبی که از آنها بسازی.
Unity خودش همین پترن است. GameObject ظرف است و هر MonoBehaviour یک component. componentها با GetComponent/TryGetComponent همدیگر را پیدا میکنند، ترجیحاً از طریق interfaceهایی مثل IDamageable، و [RequireComponent] وابستگیهای اجباری را اعلام میکند تا ادیتور خودش آنها را اضافه کند. حالا طراحها میتوانند بدون دست زدن به کد، در یک prefab نوع دشمن تازه بسازند.
کِی به کار میآید؟
بهطور پیشفرض برای هر چیزی که در scene زندگی میکند از آن استفاده کن. هر وقت خواستی class X : SomethingEnemy بنویسی فقط برای اینکه یک توانایی اضافه کنی، احتمالاً آن توانایی باید component خودش باشد.
مخصوصاً وقتی طراحها باید محتوا بسازند خیلی ارزشمند است: یک کتابخانه از componentهای Health، Mover، Shooter، Pickup و Interactable بهعلاوهٔ prefab variantها به آنها اجازه میدهد در ادیتور موجودیتهای تازه اختراع کنند.
آنقدر خردش نکن که یک مفهوم واحد بین ده component پخش شود که مدام سراغ هم میروند. اگر دو تکه همیشه با هم میآیند و بیشتر stateشان مشترک است، یک component از دو تا خواناتر است.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// The AI component and entry point. It needs a Mover, uses a Shooter
/// only if one is attached, and reacts to Health if present. The same
/// brain drives a walker, a drone (Mover set to flying) or an unarmed scout.
/// </summary>
[RequireComponent(typeof(Mover))]
public class EnemyBrain : MonoBehaviour
{
[SerializeField] private Transform player;
[SerializeField] private float keepDistance = 6f;
private Mover mover;
private Shooter shooter; // optional
private Health health; // optional
private void Awake()
{
mover = GetComponent<Mover>();
TryGetComponent(out shooter);
TryGetComponent(out health);
}
private void OnEnable()
{
if (health != null) health.Died += OnDied;
}
private void OnDisable()
{
if (health != null) health.Died -= OnDied;
}
private void Update()
{
Vector3 away = (transform.position - player.position).normalized;
mover.Destination = player.position + away * keepDistance;
if (shooter != null)
shooter.TryShoot(player);
}
private void OnDied()
{
enabled = false;
mover.Destination = null;
}
}
}using System;
using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>Anything that can take a hit. Other components talk to it through this interface.</summary>
public interface IDamageable
{
void TakeDamage(int amount);
}
/// <summary>
/// One responsibility: hit points. It does not know whether its owner
/// walks, flies, shoots or is a crate.
/// </summary>
[DisallowMultipleComponent]
public class Health : MonoBehaviour, IDamageable
{
[SerializeField] private int maxHealth = 50;
public int Current { get; private set; }
public event Action Died;
private void Awake() => Current = maxHealth;
public void TakeDamage(int amount)
{
if (Current <= 0) return;
Current = Mathf.Max(0, Current - amount);
if (Current == 0)
Died?.Invoke();
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// One responsibility: moving toward a destination. Whoever decides where
/// to go (an AI, the player, a cutscene) just sets Destination.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class Mover : MonoBehaviour
{
[SerializeField] private float speed = 4f;
[SerializeField] private bool flying;
private Rigidbody body;
public Vector3? Destination { get; set; }
private void Awake()
{
body = GetComponent<Rigidbody>();
body.useGravity = !flying;
}
private void FixedUpdate()
{
if (Destination is not Vector3 target) return;
Vector3 to = target - body.position;
if (!flying) to.y = 0f;
if (to.sqrMagnitude < 0.01f)
{
Destination = null;
return;
}
body.MovePosition(body.position + Vector3.ClampMagnitude(to, speed * Time.fixedDeltaTime));
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// One responsibility: firing at a target. It finds damageable things
/// through the IDamageable interface, never through a concrete class.
/// </summary>
public class Shooter : MonoBehaviour
{
[SerializeField] private int damage = 10;
[SerializeField] private float range = 12f;
[SerializeField] private float cooldown = 0.8f;
private float nextShotTime;
public bool TryShoot(Transform target)
{
if (Time.time < nextShotTime) return false;
Vector3 origin = transform.position;
Vector3 dir = target.position - origin;
if (!Physics.Raycast(origin, dir.normalized, out RaycastHit hit, range)) return false;
if (hit.collider.TryGetComponent(out IDamageable victim))
victim.TakeDamage(damage);
nextShotTime = Time.time + cooldown;
return true;
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: یک سلسلهمراتب دشمن که برای هر ترکیب یک زیرکلاس تازه میخواهد. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
کلاس ShootingFlyingEnemy از FlyingEnemy ارث میبرد و آن هم از Enemy. سلامتی، حرکت و شلیک در یک زنجیره به هم جوش خوردهاند و هر سطح Move را override میکند یا فیلدهایی به آنچه از والدش گرفته اضافه میکند.
یک دشمن پیادهٔ تیرانداز به زیرکلاس دیگری نیاز دارد که کد شلیک را کپی کند. برجکی هم که شلیک میکند ولی هیچوقت حرکت نمیکند نمیتواند از ShootingFlyingEnemy استفاده کند، مگر اینکه پروازی را به ارث ببرد که نمیخواهد. هر درخواست طراحی تازه تعداد کلاسها را چند برابر میکند و هر اصلاح در کد شلیک باید در همهٔ کپیها تکرار شود.
✓ چه چیزی عوض شد؟
- زنجیره حذف شده است:
Health،FlyerوGunسهMonoBehaviourمستقلاند و یک تیرانداز پرنده فقط یک GameObject است که هر سه را دارد. - حرکت پشت interface کوچک
IMoverقرار گرفته است.Gunیک بار باTryGetComponentپیدایش میکند؛ پس همانGunروی یک پرنده، یک دشمن پیادهٔ آینده یا برجکی بدون هیچ mover کار میکند. - کد شلیک و سلامتی خط به خط همان است؛ فقط در کلاس خودش زندگی میکند. پس نوعهای تازهٔ دشمن بهجای نوشته شدن به شکل زیرکلاس، در یک prefab سرهم میشوند.
using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// Without components: every new kind of enemy is a new subclass, and
/// each one inherits everything above it, needed or not.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] protected int maxHealth = 50;
[SerializeField] protected float speed = 3f;
protected int health;
protected virtual void Awake() => health = maxHealth;
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0) Destroy(gameObject);
}
protected virtual void Move(Vector3 target)
{
Vector3 to = target - transform.position;
to.y = 0f;
transform.position += Vector3.ClampMagnitude(to, speed * Time.deltaTime);
}
}
public class FlyingEnemy : Enemy
{
[SerializeField] protected float altitude = 4f;
protected override void Move(Vector3 target)
{
target.y = altitude;
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
public class ShootingFlyingEnemy : FlyingEnemy
{
[SerializeField] private Transform player;
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private float cooldown = 1f;
private float nextShot;
private void Update()
{
Move(player.position);
if (Time.time >= nextShot)
{
Instantiate(bulletPrefab, transform.position, Quaternion.LookRotation(player.position - transform.position));
nextShot = Time.time + cooldown;
}
}
}
// Next sprint: ShootingWalkingEnemy, HealingFlyingEnemy, ShootingTurret (no Move)...
}using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// With components: each ability is a small MonoBehaviour. A flying
/// shooter is a GameObject with Health + Flyer + Gun, no subclass needed.
/// </summary>
public class Health : MonoBehaviour
{
[SerializeField] private int maxHealth = 50;
private int health;
private void Awake() => health = maxHealth;
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0) Destroy(gameObject);
}
}
public interface IMover
{
void Move(Vector3 target);
}
public class Flyer : MonoBehaviour, IMover
{
[SerializeField] private float speed = 3f;
[SerializeField] private float altitude = 4f;
public void Move(Vector3 target)
{
target.y = altitude;
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
public class Gun : MonoBehaviour
{
[SerializeField] private Transform player;
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private float cooldown = 1f;
private float nextShot;
private IMover mover; // optional: a turret has none
private void Awake() => TryGetComponent(out mover);
private void Update()
{
mover?.Move(player.position);
if (Time.time >= nextShot)
{
Instantiate(bulletPrefab, transform.position, Quaternion.LookRotation(player.position - transform.position));
nextShot = Time.time + cooldown;
}
}
}
// A Walker : MonoBehaviour, IMover is one more small file; every combination is free.
}مزایا و معایب
+ مزایا
- تواناییها آزادانه ترکیب میشوند؛ پس تعداد کلاسها بهصورت خطی با قابلیتها رشد میکند، نه با تکتک ترکیبهایشان.
- هر component کوچک، متمرکز و بهتنهایی قابل تست است؛ باگ
Healthیک بار برای بازیکن، دشمن و جعبه با هم درست میشود. - موجودیتها میتوانند در زمان اجرا با
AddComponentیا با فعال و غیرفعال کردن componentها رفتاری به دست بیاورند یا از دست بدهند؛ کاری که یک سلسلهمراتب وراثت نمیتواند انجام دهد.
− معایب
- رفتار بین چند اسکریپت پخش است؛ پس فهمیدن یک موجودیت یعنی خواندن کل فهرست componentهایش، نه فقط یک کلاس.
- componentهایی که به هم وابستهاند باید به هم وصل شوند؛ صدا زدن بیحساب
GetComponentدر هر فریم وقت میگیرد و componentهای جاافتاده فقط در زمان اجرا خطا میدهند. - ارتباط بین componentها (چه کسی به
Healthمیگوید انیمیشن ضربه را پخش کند؟) یک قرارداد لازم دارد، مثل eventها یا interfaceها؛ وگرنه به وابستگیهای دلبخواهی تبدیل میشود.
چند نکتهٔ کاربردی
- ۰۱نتیجهٔ پیدا کردن componentها را در
Awakecache کن.GetComponentرا فقط وقتی درUpdateصدا بزن که آن component واقعاً ممکن است وسط بازی عوض شود. - ۰۲برای وابستگیهای اجباری از
[RequireComponent(typeof(Rigidbody))]و برای وابستگیهای اختیاری ازTryGetComponentاستفاده کن تا برجکی کهMoverندارد هم کار کند. - ۰۳از طریق interfaceها با componentهای دیگر حرف بزن (
TryGetComponent(out IDamageable d)) تا جعبه، بازیکن و باس بدون کلاس پایهٔ مشترک بتوانند آسیب بخورند. - ۰۴برای «اتفاقی افتاد» eventها (
Health.Died) و برای «همین الان این کار را بکن» فراخوانی مستقیم را ترجیح بده؛ اینطوری componentها در جزئیات داخلی همدیگر دست نمیبرند. - ۰۵وراثت کمعمق را هر جا واقعاً کمک میکند نگه دار، مثلاً یک
Weaponانتزاعی با چند سلاح مشخص. ترکیب یعنی دوری از درختهای عمیق، نه ممنوع کردن وراثت.