Menu
CoddyTech

Recap: Roll the Loot

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 22 of 64.

This chapter put serializable classes, lists and enums in the Inspector, and the chest's table uses all three. Now the chest rolls on it.

challenge icon

Challenge

Easy

Make Space open the chest and drop one item by weight.

  1. Write public LootEntry Pick(int roll): walk table; return the entry when roll is below its weight, else subtract the weight. After the loop, return null;.
  2. On Space, pick with Random.Range(0, TotalWeight()), spawn its prefab 1.5 units above the chest and log entry.rarity + ": " + entry.itemName.

Press Play and Space: mostly Common: Apple or Bread. Then Check.

Try it yourself

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

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

[System.Serializable]
public class LootEntry
{
    public string itemName;
    public GameObject prefab;
    public Rarity rarity;
}

public class LootChest : MonoBehaviour
{
    public List<LootEntry> table;

    public int WeightOf(Rarity rarity)
    {
        switch (rarity)
        {
            case Rarity.Common: return 10;
            case Rarity.Rare: return 4;
            case Rarity.Epic: return 2;
            case Rarity.Legendary: return 1;
        }
        return 0;
    }

    public int TotalWeight()
    {
        int total = 0;
        foreach (LootEntry entry in table) total += WeightOf(entry.rarity);
        return total;
    }

    // Pick(int roll) and opening the chest with Space go here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity

Practice on your own: Unity playground