Search Unity

Default serialization of fields for object lists

Discussion in 'Scripting' started by jrhee, Dec 14, 2017.

  1. jrhee

    jrhee

    Joined:
    Dec 5, 2013
    Posts:
    74
    Is there any way to have default field values set in the inspector for lists of objects? I noticed default values are set automatically for objects declared individually in MonoBehaviours, but not for lists/arrays. For example:

    Code (csharp):
    1.  
    2. [System.Serializable]
    3. public class MyClass
    4. {
    5.     public string testString = "Hello world";
    6. }
    7.  
    8. // ...
    9.  
    10. public class MyComponent : MonoBehaviour
    11. {
    12.     public MyClass testInstance;
    13.     public List<MyClass> testList;
    14. }
    15.  
    In the inspector, testString is set to "Hello world" for testInstance but not for elements in testList.

    Is there a way to work around Unity serialization to have new list element fields set to defaults, or a default constructor be called?
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    No idea for a proper (better) solution, but all I could think of was this:
    Code (csharp):
    1.  
    2. [ContextMenu("MyAddMethod")]
    3.     public void AddItem()
    4.     {
    5.         testList.Add(new MyClass());
    6.     }