Surprises with Scriptable Objects and private fields

It is general knowledge that the Unity Inspector shows every that is serialized unless it is hidden with the [System.NonSerialized] attribute. If we want a private field to be serialized and visible we add the [SerializeField] attribute. So far so good.

Now here comes the surprise.
For ScriptableObjects, if used in the Editor, private fields are always serialized. As long as you remain in the Editor, that value will persist even through play mode state changes.

using UnityEngine;

public class DemoObject : ScriptableObject
{
    // This is actually serialized if we are in the Editor!!!
    private string DummyTextA;

    // Only this one is NOT serialized.
    [System.NonSerialized]
    private string DummyTextB;
}

If you are using Scriptable Objects, use [System.NonSerialized] to make sure your private parts are actually kept private.

Asset Recommendations

I hope you liked this tiny tidbit of information. Here are some assets that may be useful to you. If you get one of them then some of the money will go towards funding this project. Thank you.

Disclosure: This text may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we have recommended. While clicking these links won't cost you any money, they will help fund this project! The links are created by Unity and Partnerize (Unity's affiliate partner).

Related Articles

Start with first scene script

Sometimes when working on a scene in Unity you do not necessarily want the play mode to start with that scene (which is the default behavior).
Read article ..

Composition vs Inheritance in Unity

Although inheritance is a powerful tool, composition is quite often the better approach. This article explores what happens if composition is used whenever possible.
Read article ..