What Is It?
Type Object splits a game entity into two parts: the instance (this particular goblin, with its own current health and position) and its type (what every goblin has in common: max health, speed, attack, colour, prefab). The instance keeps a reference to its type and reads the shared values through it.
In Unity the type is almost always a ScriptableObject. An EnemyType asset called Orc holds the numbers, and one plain Enemy MonoBehaviour handles every kind of enemy. Making a new kind of monster becomes Create → Patterns → Enemy Type, not a new C# file and a recompile.
Because hundreds of instances point at the same asset, editing that asset changes all of them at once. Bump Orc.speed in the Inspector during Play Mode and every orc on screen speeds up on the next frame, because Enemy.Update reads type.Speed instead of a copy.
When Is It Used?
Use it when you have many "kinds" of something that differ mostly in data: enemies, weapons, items, spells, tiles, crop types, card definitions.
It pays off as soon as designers need to add or rebalance kinds without waiting on a programmer. A spreadsheet importer or a modding pipeline can create types at runtime too, since a type is just data.
Skip it when kinds really differ in behaviour, not numbers. A boss with a unique three-phase fight is not a row in a table; give it code (or combine Type Object with Strategy or Subclass Sandbox for the behaviour part).
Interactive Demo
Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.
Code
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);
}
}
}Before & After
Real-world smell: one subclass per enemy with hard-coded stats. Here is the code without the pattern, the refactored version, and the exact diff between them.
! What’s wrong with it?
Goblin, Orc and Troll each subclass Enemy only to return different numbers from MaxHealth, Speed and Attack. There is no real difference in behaviour between them.
Every balance pass is a code change and a domain reload, designers cannot add a "Skeleton" without a programmer, and twenty kinds of enemy means twenty near-identical classes and twenty prefabs wired to the right script.
✓ What changed
- The three subclasses are deleted;
Enemyis no longerabstract. - A new
EnemyTypeScriptableObject holdsmaxHealth,speedandattackas serialized fields, andEnemygets a[SerializeField] private EnemyType typereference. - The abstract properties become one-line pass-throughs such as
Speed => type.Speed, soUpdateandTakeDamageare unchanged. - Goblin, Orc and Troll now exist as assets, so tuning or adding a kind happens in the Inspector, even in 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;
}
}Advantages & Disadvantages
+ Advantages
- New kinds need no code and no recompile; designers own the content.
- Shared data is stored once per type, not once per instance, which saves memory with large crowds.
- Live tuning: one edit to the asset updates every instance that references it.
− Disadvantages
- Behaviour is harder to vary than data; you end up adding flags or strategy fields to the type to express differences.
- Edits to a
ScriptableObjectin Play Mode persist in the Editor, which surprises people the first time a test tweak ships. - Two objects instead of one: you must keep "per-type" and "per-instance" fields clearly separated, or instance state leaks into the shared asset.
Tips
- 01Never write per-instance state (like
currentHealth) into the type asset. Every instance would share it, and in the Editor it would be saved to disk. - 02Read type values through the reference (
type.Speed) rather than caching them inAwake, unless you deliberately want instances to ignore later tweaks. - 03Give the type a factory method such as
EnemyType.Spawnso creating an instance always goes through its kind andInitis never forgotten. - 04For inheritance between types (an "Elite Orc" that overrides only speed), add an optional
parentfield and fall back to it for unset values. - 05This is Flyweight with a gameplay focus: Flyweight is about sharing memory, Type Object is about letting data define kinds.