Unity Loot Tables: Weighted Random Drops With ScriptableObjects

Illustration: a treasure chest bursting with glowing items of different rarity colors

Every RPG, roguelike and looter shooter needs to answer one question: when this enemy dies, what drops? Hard-coding “10% chance of a sword” into each enemy gets messy fast. A Unity loot table built on ScriptableObjects and weighted random selection keeps drop chances in data, so designers can tune them without touching code. This guide builds one with rarity tiers, multiple rolls, guaranteed drops, a pity counter and a pickup spawner.

How Weighted Random Works

A plain Random.Range picks every item equally. For loot you want common items often and rare ones rarely. The standard trick is weights. Give each entry a number, add them up, pick a random number from 0 to that total, and walk the list until you pass it.

Say Coin has weight 70, Potion 25 and Legendary Sword 5. The total is 100. Roll a number between 0 and 100. Under 70 is a coin, 70 to 95 is a potion, above 95 is the sword. The weights do not have to add up to 100. Weights of 700, 250 and 50 behave identically, which is why weights are easier to maintain than percentages: adding a new item does not force you to rebalance everything else.

Item Data and Rarity

Each item is a ScriptableObject asset. If you have not used them before, the ScriptableObjects guide covers the basics, and the inventory system tutorial uses the same pattern for items you can hold.

using UnityEngine;

public enum Rarity { Common, Uncommon, Rare, Epic, Legendary }

[CreateAssetMenu(menuName = "Loot/Item")]
public class LootItem : ScriptableObject
{
    public string displayName;
    public Sprite icon;
    public Rarity rarity;
    public GameObject pickupPrefab;   // what appears in the world
}

Create assets with Assets > Create > Loot > Item. Rarity is just a label here. Its main uses are the pickup glow color, the UI border and the pity counter below. The weight lives on the table, not on the item, because the same item can be common in one chest and rare in another.

The Loot Table Asset

using System;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "Loot/Loot Table")]
public class LootTable : ScriptableObject
{
    [Serializable]
    public class Entry
    {
        public LootItem item;
        [Min(0f)] public float weight = 1f;
        public int minAmount = 1;
        public int maxAmount = 1;
    }

    [Serializable]
    public class Guaranteed
    {
        public LootItem item;
        public int amount = 1;
    }

    [Tooltip("Chance (0 to 1) that a roll gives nothing at all")]
    [Range(0f, 1f)] public float nothingChance = 0.2f;

    [Min(1)] public int rolls = 1;
    public List<Entry> entries = new List<Entry>();
    public List<Guaranteed> guaranteed = new List<Guaranteed>();

    public struct Drop
    {
        public LootItem item;
        public int amount;
    }

    public void Roll(List<Drop> results)
    {
        foreach (var g in guaranteed)
            if (g.item != null) results.Add(new Drop { item = g.item, amount = g.amount });

        for (int i = 0; i < rolls; i++)
        {
            if (UnityEngine.Random.value < nothingChance) continue;
            Entry e = PickEntry();
            if (e == null) continue;
            int amount = UnityEngine.Random.Range(e.minAmount, e.maxAmount + 1);
            results.Add(new Drop { item = e.item, amount = amount });
        }
    }

    Entry PickEntry()
    {
        float total = 0f;
        foreach (var e in entries) total += e.weight;
        if (total <= 0f) return null;

        float roll = UnityEngine.Random.value * total;
        foreach (var e in entries)
        {
            if (roll < e.weight) return e;
            roll -= e.weight;
        }
        return entries[entries.Count - 1];   // float rounding safety net
    }
}

A few details worth noting:

  • UnityEngine.Random is written in full because using System; also brings in System.Random, and the two names clash. Without the prefix you get the compiler error “‘Random’ is an ambiguous reference between ‘UnityEngine.Random’ and ‘System.Random’”.
  • Random.Range(int, int) has an exclusive upper bound, which is why the code uses maxAmount + 1. The float version is inclusive. Mixing these up is a classic off-by-one.
  • Results go into a list you pass in, so you can reuse one list and avoid allocating a new array on every kill. See the garbage collection guide for why that matters in busy games.
  • The loop subtracts each weight from the roll, which is the “walk the list” step. The last line only runs if floating point error leaves the roll just past the end.

Spawning the Drops

Attach a small component to anything that can drop loot: enemies, crates, chests. It holds a reference to a table and spawns pickups when told to.

using System.Collections.Generic;
using UnityEngine;

public class LootDropper : MonoBehaviour
{
    [SerializeField] LootTable table;
    [SerializeField] float scatterRadius = 0.6f;

    static readonly List<LootTable.Drop> buffer = new List<LootTable.Drop>();

    public void Drop()
    {
        buffer.Clear();
        table.Roll(buffer);

        foreach (var d in buffer)
        {
            for (int i = 0; i < d.amount; i++)
            {
                Vector2 offset = Random.insideUnitCircle * scatterRadius;
                Vector3 pos = transform.position + new Vector3(offset.x, 0.5f, offset.y);
                Instantiate(d.item.pickupPrefab, pos, Quaternion.identity);
            }
        }
    }
}

Call Drop() from your death code. If you use the IDamageable pattern from the damage system guide, an OnDeath event or the place where you destroy the enemy is the right spot. The pickups themselves are ordinary collectibles, as built in the coins and pickups guide. Each pickup prefab only needs to know which LootItem it represents so the player can add it to an inventory on contact.

The scatter keeps stacked drops from landing in one spot. For 2D, use X and Y instead of X and Z. For large drop counts, such as gold, drop one pickup with an amount value instead of spawning dozens of objects.

Guaranteed Drops and Pity

Pure random is honest but cruel. A player can go 80 kills without a rare drop and quit. Two tools soften that.

Guaranteed drops are already in the table. A boss table with a guaranteed key item always drops it, then rolls the weighted list for extras.

A pity counter raises the odds after each miss and resets after a hit. The simplest form forces a rare after N misses:

public class PityTracker
{
    readonly int rareEvery;      // guarantee a Rare or better at least once per N drops
    int missesInARow;

    public PityTracker(int rareEvery) { this.rareEvery = rareEvery; }

    public bool IsRareOrBetter(Rarity r) => r >= Rarity.Rare;

    // call with the result of a normal roll
    public bool ShouldForceRare(LootItem rolled)
    {
        if (rolled != null && IsRareOrBetter(rolled.rarity))
        {
            missesInARow = 0;
            return false;
        }
        missesInARow++;
        if (missesInARow >= rareEvery)
        {
            missesInARow = 0;
            return true;
        }
        return false;
    }
}

When ShouldForceRare returns true, roll again using only the entries whose rarity is Rare or above, and use that item instead. Keep one tracker per player, not per enemy, so the counter follows the player across fights. Store it with the rest of your progress using the JSON save system, or players can reset pity by restarting the game.

Another approach is raising weights gradually: add 1 to every rare weight after each miss and reset on a hit. It feels smoother but is harder to reason about, so start with the hard cap.

📚 Game design reading

Drop rates and reward pacing are design problems as much as code. Our list of programming and game design books has good picks on reward loops.

Testing the Odds

Never trust drop rates you have not simulated. Add this context menu method to LootTable and run it from the Inspector:

[ContextMenu("Simulate 10000 Rolls")]
void Simulate()
{
    var counts = new Dictionary<LootItem, int>();
    var results = new List<Drop>();
    for (int i = 0; i < 10000; i++)
    {
        results.Clear();
        Roll(results);
        foreach (var d in results)
            counts[d.item] = counts.TryGetValue(d.item, out int c) ? c + d.amount : d.amount;
    }
    foreach (var kv in counts)
        Debug.Log($"{kv.Key.displayName}: {kv.Value / 100f:0.0} per 100 rolls", this);
}

Right-click the asset’s header in the Inspector and choose Simulate 10000 Rolls. The console shows how many of each item dropped per 100 rolls. If a “5%” legendary shows 12 per 100, the weights are not what you think. Remember that an entry’s real chance is its weight divided by the total weight, then multiplied by 1 - nothingChance.

Troubleshooting

‘Random’ is an ambiguous reference between ‘UnityEngine.Random’ and ‘System.Random’

You have both using System; and using UnityEngine;. Write UnityEngine.Random or remove the System using.

The same item drops every time

One entry has a huge weight compared with the rest, or the others have weight 0. Check the weights in the table. Another cause is the same object being rolled in a loop with Random.InitState set to a fixed seed.

Rare items drop far too often (or never)

Weights are relative, not percentages. A weight of 5 next to weights of 1 and 2 is the most common item. Use the simulation method and adjust.

NullReferenceException in Drop()

The table or an item’s pickupPrefab is not assigned. Make sure every entry has an item and every item has a prefab.

Drops fall through the ground or fly away

The pickup is spawned inside a collider, or has a Rigidbody with an extreme force. Spawn a little above the ground and avoid spawning inside the dying enemy’s collider. The falls through floor guide covers the other causes.

Drop count is one too few

Check that the integer Random.Range upper bound is exclusive, so Random.Range(1, 3) returns 1 or 2, never 3.

FAQ

Can I use an AnimationCurve instead of weights?

You can, but weights are simpler to read and tune. Curves suit things like scaling drop quality with player level.

How do I make drops depend on player level or luck?

Multiply weights at roll time. For example, scale rare weights by a luck value before summing. Pass the multiplier into Roll instead of editing the asset.

Should the table be a ScriptableObject or JSON?

ScriptableObjects give you Inspector editing, asset references and no parsing. Use JSON only if you need data to be moddable or updated without a new build.

How do I stop the same item dropping twice in one roll?

Remove the picked entry from a temporary copy of the list before the next roll, which gives you “draw without replacement”.

Do I need object pooling for pickups?

Not for a few drops. If an area spawns hundreds of pickups per second, pool them. The cost is in Instantiate and Destroy, not in the roll.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *