Private fields getting serialized
Everywhere I look, it is stated that Unity doesn't serialize private fields unless you use [SerializeField]
, for example in the Script Serialization Manual. But I am observing that all my private fields get serialized, as long as their type and the class they're in are serializable.
Example code:
using UnityEngine;
class SerializerTest : MonoBehaviour, ISerializationCallbackReceiver
{
private int x = 0;
private void Awake() {
x = 42;
}
private void OnEnable() {
Debug.Log($"OnEnable: x = {x}");
}
public void OnBeforeSerialize()
{
Debug.Log($"Before serialization: x = {x}");
}
public void OnAfterDeserialize()
{
Debug.Log($"After serialization: x = {x}");
}
}
The output after hitting run, adding a new newline in the code, and returning to the running game:
Before serialization: x = 0
After serialization: x = 0
OnEnable: x = 42
Before serialization: x = 42
After serialization: x = 42
OnEnable: x = 42
(I removed extra serialization logs that appear at game start, I guess they're artifacts from Unity instantiating the MonoBehaviour.)
The question is: Why is the value of x
preserved after the hot reload? It seems it got serialized and deserialized successfully despite being private
. Did the rules for serialization change? Do I miss something?
I am running Unity 2020.3.17f1
.