How to prevent a list from being cleared at runtime?

In the editor I’m building lists attached to C# scripts on various gameObjects. Those lists are getting cleared at the start of the game. I need to preserve the data they contain…

Arrays don’t have this problem - that is, I can populate arrays in-editor, and the data persists as the game runs. But lists are vastly better suited to my use case.

Anyone know why lists are getting cleared on start, but arrays aren’t?

Edit: Make sure you are calling EditorUtility.SetDirty on the changed object. This lets the editor know that a script has changed the value of an object (or really anything has changed the value of an object) and that it needs to be serialized out to disk.


Verify that you are not creating the lists in the Start method. A common error is to do this:

List<int> somelist;
void Start()
{
  somelist = new List<int>();
}

This will allow you to populate the list in the editor, but of course as soon as you run the game…boom! Data gone. Instead, do it this way:

List<int> someList;
void Start()
{
  if(someList == null)
  {
    someList = new List<int>();
  }
}

This way if it wasn’t set in the editor it won’t crash, but if it was set in the editor it won’t overwrite the data.

This isn’t a great solution, but it appears that after I populate the fields of the array with an editor script, I can then “lock them in” by going to the component (in the inspector) and selecting “copy component” then “paste component values”. That will cause all entered fields to go bold-facce, and likewise to persist when the game runs.

Seems like some kind of bug where the editor doesn’t treat fields edited by script as first-class-citizens, so to speak.

I’d certainly welcome feedback or suggestions to make this cleaner…

You can use a null-coalescing operator for that null check - tidies up the code nicely:

void Start()
 {
         someList ??= new List<int>();
 }