Unity (2020.3.32f1) seems to be ignoring the initialization values I give to certain class members.
private string test = "test";
private int intTest = 10;
private long longTest = 1000L;
private double doubleTest = 1;
-
When running, test becomes null, and all of the other primitives become 0. The behavior seems to suggest that unity is serializing the entire class and dropping the “= x” portion, even for private members.

-
I am not setting their values anywhere else in the scripts or the prefab. There are other public values set by a prefab in this script.
-
I have tried adding [NonSerialized] to them with no success.
Is this supposed to work or is it necessary to initialize within Start()?
You’d have to share more context here. Without it, it’s hard to say anything. Show the whole script.
It should work, these fields should be initialised when entering play or during domain reloads. I believe Unity does this by quickly serialising the fields, so marking them [NonSerialized] probably won’t help here.
More context is needed here though.
From my testing on 2023.35.f1, Unity ignores the initializer values if the serializable class has a constructor. One would instead need to initialize the field manually on the unity Object instead.
So long as a serializable class has a parameterless constructor, Unity will call that when instancing it during serialization.
It it doesn’t, then it creates an instance with default values.
So in practice, this code:
public class TestScriptableObject : ScriptableObject
{
public SomeClass SomeClassA;
public SomeClass SomeClassB = new();
public SomeClass2 SomeClass2A;
public SomeClass2 SomeClass2B = new(10, 1.0f);
}
[System.Serializable]
public class SomeClass
{
public int SomeInt = 10;
public float SomeFloat = 1.0f;
}
[System.Serializable]
public class SomeClass2
{
public int SomeInt = 10;
public float SomeFloat = 1.0f;
public SomeClass2(int someInt, float someFloat)
{
SomeInt = someInt;
SomeFloat = someFloat;
}
}
Gets this result:
1 Like