System.Serializable on custom class refuses to init as NULL

Just ran into a problem with my custom classes. I found a blog that points out the exact problem. But can find a solution or work around. I guess I could check if a property inside the class that should not be null is null.

Here are details from the problem as explained in the blog:

When you mark a class as Serializable,
Unity will automatically instantiate
an object for any field you define of
that class type. Even if you want
that field to be null.

Example:

[System.Serializable]
public class SerializableDataClass
{
    public int SomeValue = -1;
}

public class NormalDataClass
{
    public int SomeOtherValue = -1;
}

public class MyMonoBehaviour : MonoBehaviour
{
    // Will Never Be Null, not expected
    public SerializableDataClass DataObj1 = null;

    // Will Remain Null Until Assigned, as expected
    public NormalDataClass DataObj2 = null
}

DataObj1 will automatically have an
object created and assigned to it,
even if you initialize it to null and
try setting it to null in other areas
like Awake()/Start()/Update().

Full blog post: Random Thoughts of a Game Developer: System.Serializable attribute annoyances in Unity3D

Well, you simply have to understand that the serialization system treats System.Serializable classes like structs, that’s it. If you want the class to be serialized in the editor you have to live which that.

The only alternative is to use an array instread of a simple variable:

public class MyMonoBehaviour : MonoBehaviour
{
    public SerializableDataClass[] DataObjs;
}

Of course “DataObjs” won’t be null either, but it can have a length of 0