Serializable Class Automatically Constructed OnAwake?

Hi I defined a class like below

Initially, I didn’t give it [Serializable]

And I used it in here:

So if without Serializable, when game starts, I need line 26 to construct this object first, and then I can execute line 27. Otherwise, I would get NullObjectFoundException. However, after I give [Serializable], I don’t need line 26. It can pass. And from inspector, I can see this dmg attribute:

I don’t know why after giving [Serializable], I don’t need to construct it anymore before using it. Anyone can explain to me? Thanks

There are two factors- making it serializable, and holding the reference in a UnityEngine.Object-derived class (MonoBehaviour/Component/ScriptableObject). The reason is that Unity automatically creates initial copies of serializable object types for use in the inspector, so that you can enter values and have it initialized the way that you want, as your last screenshot shows. If it’s not serialized, it’s ignored by Unity, you can’t edit it into the inspector and no initial copy is created for you, meaning you have to create it yourself.

1 Like