【问题标题】:System.Serializable not working on a List<MyClass> in Unity?System.Serializable 不能在 Unity 中的 List<MyClass> 上工作?
【发布时间】:2018-10-11 15:36:56
【问题描述】:

我正在创建一个战利品系统。我几乎快到最后了,剩下的就是在我的Enemy 脚本的检查器中填写DropTable。出于某种原因,我的 DropTable 脚本正在序列化,但是我的 LootDrop 类不是。我的课程基本上是这样设置的:

DropTable类:

[System.Serializable]
public class DropTable
{
 public List<LootDrop> loot = new List<LootDrop>();

 public Item GetDrop()
 {
    int roll = Random.Range(0, 101);
    int chanceSum = 0;
    foreach (LootDrop drop in loot)
    {
        chanceSum += drop.Chance;
        if (roll < chanceSum)
        {
            return ItemDatabase.Instance.GetItem(drop.itemSlug); //return the item here
        }
    }
        return null; //Didn't get anything from the roll
 }
}

LootDrop类:

[System.Serializable]
public class LootDrop
{
    public string itemSlug { get; set; }
    public int Chance { get; set; }
}

基本上,我的DropTable 只包含LootDrop 的列表。但是,我无法从检查员访问 List&lt;LootDrop&gt; 内的各个 LootDrop 实例。我所做的只是在我的Enemy 脚本上创建一个public DropTable 变量。我觉得我以前做过类似的事情并且没有问题。我在这里做错了吗?我真的希望DropTable 成为与我的敌人分开的类,因为敌人不应该真正关心GetDrop() 方法。但是,如果这是唯一的方法,那么我想它必须这样做。对此问题的任何帮助将不胜感激。

【问题讨论】:

  • 如何初始化“战利品”变量?
  • @lucky 我不能,这就是问题所在。我正在尝试在检查器中对其进行初始化。我可以通过添加条目来操作列表本身,但它不会让我自己编辑条目。
  • 您能否说明DropTable 的实例是如何声明和使用的,以及您当前在“检查器”选项卡上看到的屏幕截图?

标签: c# unity3d serialization


【解决方案1】:

Unity 将序列化字段,而不是属性。切换到字段:

[Serializable]
public class LootDrop
{
    public int Chance;
}

或者使用序列化的支持字段:

[Serializable]
public class LootDrop
{
    public int Chance
    {
        get { return _chance; }
        set { _chance = value; }
    }

    [SerializeField]
    private int _chance;
}

【讨论】:

  • 我认为这也是问题,但 OP 声称 LootDrop 没有被序列化,而不是说 LootDrop 中的变量没有被序列化。
  • @Programmer 那是我的错误,我什至没有想到它是没有序列化的变量。我只是假设这是整个班级。
  • 完全没问题
【解决方案2】:

您应该在尝试添加项目之前初始化 loot 变量。

[System.Serializable]
public class DropTable
{
    public List<LootDrop> Loot;

    public DropTable()
    {
        Loot = new List<LootDrop>();
    }
}

另外,请注意命名约定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2021-02-07
    • 2019-01-04
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多