1

I've created a ScriptableObject class MySO that gets modified in its Awake() function. I also added EditorUtility.SetDirty(this); as its last command. The class has a List<someOtherClass> myList field. During the Awake function, I add a couple instances to this list.

When creating a new instance of MySO through the AssetMenu, at first, it seems to display the populated list correctly in the Inspector (basically Awake() executes fine), but the list empties the moment I click anywhere or press Enter. It's only after restarting Unity that the changes show up.

Everything relevant is either public or [Serializable].

[CreateAssetMenu(fileName = "NewMySO", menuName = "MySO")]
[System.Serializable]
public class MySO : ScriptableObject
{
    public List<someOtherClass> someOtherClassList;
    private void Awake()
    {
        //-------------------------
        //add instances to someOtherClassList
        //--------------
        EditorUtility.SetDirty(this);
        //AssetDatabase.SaveAssets(); //Didn't help
        //AssetDatabase.Refresh(); // Didn't help
    }
    
}

I've tried adding AssetDatabase.SaveAssets() and AssetDatabase.Refresh() too after SetDirty(this). Neither work, and the first one leads to errors due to restrictions during asset importing when restarting Unity.

Any help'd be appreciated.

1 Answer 1

0

It has been years since I last touched Unity but as far as I remember it does use Mono runtime for scripting so it should follow the rules of C# members of class type objects being initialized to null.

So basically in your case what happens is→ ※ You create you Scriptable object ※ Unity calls its Awake method ※ Since someOtherClassList is null, you get an error ※ Nothing shows up in inspector

What you should do is a null check followed by instancing the objects

private void Awake() {

    if (someOtherClassList == null) {
        someOtherClassList = new List<someOtherClass>();
    }
    // Do stuff
    someOtherClassList.Add(new someOtherClass() { });
}

As you can see here, now it shows up

enter image description here

1
  • Sadly this doesn't follow the problem. For starters, the list is not null: In fact, the moment the scriptable object is created its list is populated correctly and displayed in Inspector. It is only AFTER interacting with the interface in any way that the object restarts to default, which gets "fixed" only by restarting Unity. I will edit the question to clarify this. Commented Jul 5 at 18:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.