回顾:抽取战利品
本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 22 课,共 64 课。
这一章在 Inspector 中使用了可序列化的类、列表和枚举,宝箱的表格用到了这三者。现在,宝箱会根据这张表进行随机抽取。
挑战
简单让 Space 打开箱子,并按权重掉落一件物品。
- 编写
public LootEntry Pick(int roll):遍历table;当roll小于该条目的权重时,返回该条目,否则减去该权重。循环结束后,使用return null;。 - 按下 Space 时,使用
Random.Range(0, TotalWeight())进行抽取,在箱子上方 1.5 个单位处生成它的prefab,并记录entry.rarity + ": " + entry.itemName。
按“开始”,再按 Space:大多数时候会得到 Common: Apple 或 Bread。然后按“检查”。
亲手试试
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),以及按 Space 打开宝箱的功能
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Unity 游戏架构中的所有课
自己练习: Unity 在线编辑器