【问题标题】:Unity - showing self-written array in the inspectorunity - 在检查器中显示自写数组
【发布时间】:2017-06-21 09:08:27
【问题描述】:

我为 Unity 编写了自己的对象。它可以保存有关要生成的游戏对象及其数量的信息。我将它用于数组,因此数组可以有 2 个值。

public class ChestValue // my own object for "Arrays with 2 values"
{
    public ChestValue(GameObject prefab, int count) // fill the data
    {
        ItemToSpawn = prefab;
        SpawnCount = count;
    }

    public GameObject ItemToSpawn { get; private set; }
    public int SpawnCount { get; private set; }
}

这么写

[SerializeField]
ChestValue[] information;

不起作用,对象未显示在检查器中。

我知道,ChestValue 是一个对象。但是有没有办法存档呢?

喜欢编写自己的数组/元组?

【问题讨论】:

    标签: c# arrays unity3d


    【解决方案1】:

    是的,只需将 [System.Serializable] 装饰添加到类的顶部:https://docs.unity3d.com/ScriptReference/Serializable.html

    但是,您可能需要向您的类添加一个默认构造函数才能使其工作,并且您需要使用普通变量切换属性 ItemToSpawn 和 SpawnCount 以便检查器可以查看和序列化它们(我认为您也可以拥有属性但它需要更多地修改编辑器代码)。

    [System.Serializable] // tells unity that this class is serializable and therefore it can show up in the inspector
    public class ChestValue 
    {
         // Pretty sure you need a default constructor as the class is serializable
        public ChestValue(){}
        public ChestValue(GameObject prefab, int count) // fill the data
        {
            ItemToSpawn = prefab;
            SpawnCount = count;
        }
    
        // switched properties to variables so the editor can 'see' them
        public GameObject ItemToSpawn;
        public int SpawnCount;
    }
    

    【讨论】:

    • 你忘了提到另一个使用属性的问题。 Unity 无法序列化属性"{ get; private set; }....
    • 我不懂你。您应该将其编辑到您的答案中,以便 OP 不会再犯该错误。你现在只有[System.Serializable]
    • 我不确定你看到了什么,但我肯定删除了属性并在我的编辑中切换到 public GameObject ItemToSpawn/public int SpawnCount
    • 这太棒了!谢谢
    • 我知道。您的代码正确。这与正确的代码无关。这是关于告诉 OP 他们的代码有什么问题(解释你的答案)。您添加了 OP 应该添加 [System.Serializable]..为什么不添加 Unity 也不会序列化 { get; private set; }。这就是我要说的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多