Home > Back-end >  Unity EditorWindow OnGUI doesn't save data for List<string[]> types
Unity EditorWindow OnGUI doesn't save data for List<string[]> types

Time:08-11

It appears that anything I add to a List<string[]> will get added, but when I save any scripts and Unity does compiles everything, the items in the list disappears.

Here is a simple class I wrote that just displays a window and adds labels according to how many items are in the list:

    public class TestEditorWindow : EditorWindow
    {
        string windowLabel = "Test Window";
        [SerializeField] List<string[]> myList = new List<string[]>();

        [MenuItem("Tools/My Window")]
        static void Init()
        {
            TestEditorWindow myWindow = (TestEditorWindow)GetWindow(typeof(TestEditorWindow));
            myWindow.Show();
       } 

        private void OnGUI()
        {
            GUILayout.Label(windowLabel, EditorStyles.boldLabel);

            EditorGUILayout.Separator();

            GUILayout.BeginVertical("box", GUILayout.ExpandWidth(true));

            for(int i = 0; i < myList.Count; i  )
            {
                EditorGUILayout.LabelField("Stupid");
            } 

            if(GUILayout.Button(" ", GUILayout.MaxWidth(30)))
            {
                //myList.Add(new string[2]); //<-- Also tried it this way
                myList.Add(new string[] { "" });
            }

            GUILayout.EndVertical();
        }
    }

The window shows and every time I hit the button a new label is added to the window, but as soon as Unity compiles anything, the values go away.

If I change the list to List<string> it behaves as intended

I've also tried setting up the list like so and got the same results:

    [SerializeField] static List<string[]> myList;

    [MenuItem("Tools/My Window")]
    static void Init()
    {
        myList = new List<string[]>();
        TestEditorWindow myWindow = (TestEditorWindow)GetWindow(typeof(TestEditorWindow));
        myWindow.Show();
    }

Am I doing something wrong with how I'm loading the list?

CodePudding user response:

Unity cannot serialize multidimensional collections.

There is a work around though.

Create a new class that contains the string array, and create a list using that type.

[System.Serializable]
public class StringArray
{
    public string[] array;
}

and in your window use:

public List<StringArray> myList = new List<StringArray>();
  • Related