Search Unity

Non serialzed public int[] array in serilizable class

Discussion in 'Scripting' started by acropole, Nov 16, 2021.

  1. acropole

    acropole

    Joined:
    Aug 13, 2009
    Posts:
    171
    Hi,

    Why public fields are not serialzed in the following code ?

    Code (CSharp):
    1.  
    2. namespace MyNameSpace
    3. {
    4.     [Serializable]
    5.     public class MyClass
    6.     {
    7.         protected const float EPSILON = 0.000001f;
    8.  
    9.         public float[] vertices;
    10.  
    11.         public int[] triangles;
    12.  
    Despite the class itself is serialized in the monobehaviour.

    Adding SerializedField don't solve the problem.
    They show in the editor an value persist, but they are not saved when closing unity.
     
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,999
    If they are shown in the editor, they are serialized. Only serialized fields are visible in the inspector. So your issue is probably in the way you handle / change those values. Where do you actually change the values? In the inspector? If you change those values from a script / editor script you have to make sure you communicate those changes properly to the undo system. Though we don't know anything about that part. Especially it highly depends on where this class is used, where it belongs to and where it's serialized (as part of a scene or as part of an asset / prefab / scriptable object)
     
  3. davidnibi

    davidnibi

    Joined:
    Dec 19, 2012
    Posts:
    426
    Can someone explain what these Serialized things are? I've only ever used them to display in the inspector (for debugging), but there has to be more to them that that?
     
  4. acropole

    acropole

    Joined:
    Aug 13, 2009
    Posts:
    171
    Ok, adding
    if (GUI.changed) EditorUtility.SetDirty(obj);
    in my custom inspector solved the problem.

    I thought it was automatic, but in this case it's not.
     
  5. acropole

    acropole

    Joined:
    Aug 13, 2009
    Posts:
    171
  6. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,999
    So you use a custom inspector, you haven't mentioned that but I thought it may be something like that. Don't use SetDirty. It's still useable but has many drawbacks and is part of the old system that was in use 10 years ago. Also it will break for a lot of new features like prefab instances as you can read in the documentation.

    The usual way to write custom inspectors or more commonly property drawers is to use the SerializedProperty / SerializedObject construct. Of course that's not always feasable but they handled undo actions and the serialization more or less for you.

    Though if you want to manually tinker with values of your object you should use Undo.RecordObject which need to be called before you actually change the values. It will register an Undo action and also makes sure that the object is serialized.