Unity Doesnt Serialize int? field

狂风中的少年 提交于 2020-01-04 09:37:12

问题


I have a class i want to change the properties of in the editor. So i made my class System.Serializable and made the variables public that i want to be able to change.
Like so:

[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;

}

But the problem i am having is that the GapAfterElementNumer is not show up in the editor at all the other fields are. How i can i make it so that int? also shows up?


回答1:


Nullable types are not serialized in Unity Editor because it's serializer doesn't support null. There's a small workaround if you're not going to serialize this class to json using JsonUtility. The key idea is that you have to create your own nullable int. Something like

public class IntNullable 
{
     public int Value;
     public bool HasValue;
 }

Just like it's done inside .NET. Then you can create a Custom Editor for IntNullable or your UIOptionsRing. In this editor you can make a filed for int value and a button "Set Null", which will change the value of HasValue variable. And further you need to work with this custom IntNullable in your code.



来源:https://stackoverflow.com/questions/52854129/unity-doesnt-serialize-int-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!