Extra care should be taken when accessing serialized fields in a ScriptableObject instance.
If a field is marked public
or serialized through SerializeField
, changing its value is permanent. They do not reset when exiting playmode like MonoBehaviours do. This can be useful at times, but it can also make a mess.
Because of this it's best to make serialized fields read-only and avoid public fields altogether.
public class MyScriptableObject : ScriptableObject
{
[SerializeField]
int mySerializedValue;
public int MySerializedValue
{
get { return mySerializedValue; }
}
}
If you wish to store public values in a ScriptableObject that are reset between play sessions, consider using the following pattern.
public class MyScriptableObject : ScriptableObject
{
// Private fields are not serialized and will reset to default on reset
private int mySerializedValue;
public int MySerializedValue
{
get { return mySerializedValue; }
set { mySerializedValue = value; }
}
}