Unity 不序列化 int?场地

Fut*_*ake 5 serialization nullable editor public unity-game-engine

我有一个类,我想在编辑器中更改其属性。所以我创建了我的类 System.Serializable 并公开了我希望能够更改的变量。
像这样:

[System.Serializable]
public class UIOptionsRing
{
    public float Radius, DistanceBetweenPoints, StartOffset, GapInDegrees;
    public int? GapAfterElementNumer = 3; //this var doesnt show up
    public Vector3 CircleCenter;
    public GameObject CircleElementsContainer;

}
Run Code Online (Sandbox Code Playgroud)

但我遇到的问题是 GapAfterElementNumer 没有显示在编辑器中,而所有其他字段都是。我怎样才能让它int?也显示出来?

vmc*_*har 6

可空类型不会在 Unity Editor 中序列化,因为它的序列化程序不支持null. 如果您不打算使用 .json 将此类序列化为 json,则有一个小的解决方法JsonUtility。关键思想是您必须创建自己的可为空的 int。就像是

public class IntNullable 
{
     public int Value;
     public bool HasValue;
 }
Run Code Online (Sandbox Code Playgroud)

就像在 .NET 中完成的一样。然后,你可以创建一个自定义编辑器IntNullable或你的UIOptionsRing。在此编辑器中,您可以为 int 值创建一个字段和一个“Set Null”按钮,这将更改HasValue变量的值。此外,您需要IntNullable在代码中使用此自定义。

  • @CowNecromancer 这取决于你的口味。什么时候用int?在 .NET 或 Unity 中,您仍然使用 5 个字节进行操作。使用你的方法意味着有一些神奇的数字,你必须牢记这一点,我认为 1 字节的开销并不重要 (4认同)