Can Unity only serialize a field only when it's not null?

Unity’s serialization system will automatically serialize all the variables that are marked with [SerializeField], regardless of whether they are null or not. This behavior is by design, and there is no direct way to change it.

However, you can create a workaround by wrapping your variable in a custom class or struct and then implementing your own custom logic for handling null values. In this case, when your variable is null, the wrapper could simply not store anything, effectively mimicking the desired behavior.

Something like this (pseudo code):

[System.Serializable]
public class NullableWrapper<T> where T : class
{
    [SerializeField]
    private T value;

    public T Value 
    {
        get { return value; }
        set 
        {
            if (value != null) 
            {
                this.value = value;
            }
        }
    }
}

In your MonoBehaviour script, you would then use this wrapper class instead of directly using the variable you want to protect from null serialization.

public class MyMonoBehaviour : MonoBehaviour 
{
    [SerializeField]
    private NullableWrapper<MyClass> myVariable;
}

Keep in mind that this approach introduces an extra layer of complexity and can increase the difficulty of understanding and maintaining the code.

As for the deserialization cost, Unity’s serialization system is already highly optimized and, in most cases, the overhead of serializing null fields is insignificant. So, unless you are facing specific performance issues related to serialization, it might not be worth the additional complexity to try and optimize this.

Id say that the increase in complexity of your code is not worth the return. Perhaps describe in more detail why this is something you want to change in the first place, you may thinking about it incorrectly.

Thx a lot. The additional complexity is not what i want. I just want to know if there is a possible way to avoid this case.