Menu
CoddyTech

Recap: Loot Table

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 18 of 50.

challenge icon

Challenge

Easy

A treasure chest drops one item each time you press Space. Write LootChest.cs. The scene fills its loot table in the Inspector, so the names must match:

  • An enum Rarity with Common, Rare, Epic and Legendary, in that order.
  • A class LootEntry that the Inspector can show, with a string itemName, a GameObject prefab and a Rarity rarity, and on the chest a public List<LootEntry> named table. The scene's table holds the Apple and the Bread (Common), the Silver Ring (Rare), the Dragon Egg (Epic) and the Golden Crown (Legendary), in that order.
  • public int WeightOf(Rarity rarity) gives an entry's weight from its rarity: Common 10, Rare 4, Epic 2, Legendary 1. public int TotalWeight() adds up the weights of the whole table.
  • public LootEntry Pick(int roll), for a roll from 0 up to, but not including, TotalWeight(), walks the table in order, each entry covering as many rolls as its weight: rolls 0 to 9 give the Apple, 10 to 19 the Bread, 20 to 23 the Silver Ring, and so on.
  • Space rolls Random.Range(0, TotalWeight()) once, picks that entry, spawns its prefab 1.5 units above the chest and logs its rarity and name, as Rare: Silver Ring.

Press Play, open the chest a few times, then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

public class LootChest : MonoBehaviour
{
}

All lessons in Game Architecture in Unity