Home > Net >  Adding to a Generic List with Type parameter
Adding to a Generic List with Type parameter

Time:11-16

Consider the following setup:

using System;

class Shelf : ScriptableObject // << IS A SCRIPTABLE OBJECT
{
    [SerializeField] List<Jars> jars = new();

    public AddUniqueJar(Type typeOfJar)
    {
        //need to add a new object of type typeOfJar to jars. I currently do something like this:
       sentences.Add((Jar)Activator.CreateInstance(typeOfJar));
       EditorUtility.SetDirty(this);
       AssetDatabase.SaveAssets();
       AssetDatabase.Refresh();
    }
}
[Serializable]
abstract class Jar// << NOT A SCRIPTABLE OBJECT

[Serializable]
class JamJar:Jar{}

[Serializable]
class PickleJar:Jar{}

[Serializable]
class MoneyJar:Jar{}

I'd have imagined this would all be fine -, when the editor adds to the list the listview shows my new entry - but the next time my code compiles or restart a session my object loses the data for what is stored in the jars List and the ListView that queries it reports it as an empty list.

How do I get my method to add a new object of this type to the list while also serializing and maintaining that information between sessions?

CodePudding user response:

The reason the Jar classes are not serializing is because Jar is abstract.
After removing the abstract keyword, all classes are serializing like usual.

You should remove the EditorUtility and AssetDatabase code from the scriptable object, as it is not needed for this serialization to occur.

CodePudding user response:

This isn't going to work this way!

The enter image description here

Personally I would even rather save those as separate assets so you can easily maintain, remove them etc.


Or alternatively if it is really only about having different instance types you could also just instead serialize a list of an enum or type name and then rather on runtime create the instances of those accordingly.

  • Related