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
EasyMake Space open the chest and drop one item by weight.
- Write
public LootEntry Pick(int roll): walktable; return the entry whenrollis below its weight, else subtract the weight. After the loop,return null;. - On Space, pick with
Random.Range(0, TotalWeight()), spawn itsprefab1.5 units above the chest and logentry.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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground