Recap: Loot Table
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 18 of 50.
Challenge
EasyA 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
RaritywithCommon,Rare,EpicandLegendary, in that order. - A class
LootEntrythat the Inspector can show, with a stringitemName, a GameObjectprefaband a Rarityrarity, and on the chest a publicList<LootEntry>namedtable. 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, asRare: 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types