Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Doesnt Serialize int? field

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?

like image 529
FutureCake Avatar asked Oct 17 '18 11:10

FutureCake


People also ask

Does Unity serialize private fields?

When Unity serializes your scripts, it only serializes public fields.

Should I use SerializeField or public?

Public fields are serializable by default, just like the areas you mark with SerializeField. You might prefer SerializeField rather than public because you may want to see your variable in the Inspector but keep it non-accessible. There are four different statuses that your variables can have.

What does serializing a field do in Unity?

Serialization is the automatic process of transforming data structures or object states into a format that Unity can store and reconstruct later. Some of Unity's built-in features use serialization; features such as saving and loading, the Inspector window, instantiation, and Prefabs.

Should you use SerializeField Unity?

Why and when should I use [SerializeField]? Using the SerializeField attribute causes Unity to serialize any private variable. This doesn't apply to static variables and properties in C#. You use the SerializeField attribute when you need your variable to be private but also want it to show up in the Editor.


1 Answers

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.

like image 90
vmchar Avatar answered Oct 05 '22 18:10

vmchar