←All patterns
Game Programming

Type Object

Describe each kind of thing as a data object, so new kinds are assets instead of new subclasses.

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.

Type Object Pattern
Enemy classes1types3instances0
Scene · Enemy instances
Pick a type card, then spawn
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ TypeObject ›EnemySpawner.cs
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}");
            }
        }
    }
}
3 files · namespace Patterns.Game Programming.TypeObjectC# · UTF-8 · LF

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; Enemy is no longer abstract.
  • A new EnemyType ScriptableObject holds maxHealth, speed and attack as serialized fields, and Enemy gets a [SerializeField] private EnemyType type reference.
  • The abstract properties become one-line pass-throughs such as Speed => type.Speed, so Update and TakeDamage are unchanged.
  • Goblin, Orc and Troll now exist as assets, so tuning or adding a kind happens in the Inspector, even in Play Mode.
Enemies.Before.cs → Enemies.After.cs+16/−24
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.TypeObject
44 {
55 /// <summary>
6− /// Without Type Object: every kind of enemy is its own subclass
7− /// with its stats hard-coded in C#.
6+ /// With Type Object: one Enemy class. Goblin, Orc and Troll are now
7+ /// EnemyType assets that designers create and tune in the Inspector.
88 /// </summary>
9− public abstract class Enemy : MonoBehaviour
9+ public class Enemy : MonoBehaviour
1010 {
1111 [SerializeField] protected Transform target;
12+ [SerializeField] private EnemyType type;
1213
1314 protected int currentHealth;
1415
15− protected abstract int MaxHealth { get; }
16− protected abstract float Speed { get; }
17− public abstract int Attack { get; }
16+ protected int MaxHealth => type.MaxHealth;
17+ protected float Speed => type.Speed;
18+ public int Attack => type.Attack;
1819
1920 private void Awake() => currentHealth = MaxHealth;
2021
2122 private void Update()
2223 {
2324 if (target == null) return;
2425
2526 transform.position = Vector3.MoveTowards(
2627 transform.position, target.position, Speed * Time.deltaTime);
2728 }
2829
2930 public void TakeDamage(int amount)
3031 {
3132 currentHealth = Mathf.Max(0, currentHealth - amount);
3233 if (currentHealth == 0) Destroy(gameObject);
3334 }
3435 }
3536
36− // Faster Orcs? Ask a programmer, edit a number, wait for a recompile.
37− public class Goblin : Enemy
37+ // Goblin.asset, Orc.asset, Troll.asset: tuned live, no recompile.
38+ [CreateAssetMenu(menuName = "Patterns/Enemy Type")]
39+ public class EnemyType : ScriptableObject
3840 {
39− protected override int MaxHealth => 30;
40− protected override float Speed => 4f;
41− public override int Attack => 4;
42− }
41+ [SerializeField, Min(1)] private int maxHealth = 30;
42+ [SerializeField, Min(0f)] private float speed = 3f;
43+ [SerializeField, Min(0)] private int attack = 5;
4344
44− public class Orc : Enemy
45− {
46− protected override int MaxHealth => 80;
47− protected override float Speed => 2.5f;
48− public override int Attack => 10;
45+ public int MaxHealth => maxHealth;
46+ public float Speed => speed;
47+ public int Attack => attack;
4948 }
50−
51− public class Troll : Enemy
52− {
53− protected override int MaxHealth => 200;
54− protected override float Speed => 1.2f;
55− public override int Attack => 18;
56− }
5749 }

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 ScriptableObject in 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

  1. 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.
  2. 02Read type values through the reference (type.Speed) rather than caching them in Awake, unless you deliberately want instances to ignore later tweaks.
  3. 03Give the type a factory method such as EnemyType.Spawn so creating an instance always goes through its kind and Init is never forgotten.
  4. 04For inheritance between types (an "Elite Orc" that overrides only speed), add an optional parent field and fall back to it for unset values.
  5. 05This is Flyweight with a gameplay focus: Flyweight is about sharing memory, Type Object is about letting data define kinds.