lundi 14 novembre 2022

Adding to a Generic List with Type parameter

Consider the following setup:

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((FlipbookSentence)Activator.CreateInstance(typeOfJar));
       EditorUtility.SetDirty(this);
       AssetDatabase.SaveAssets();
       AssetDatabase.Refresh();
    }
}

abstract class Jar:UnityEngine.Object{} // << NOT A SCRIPTABLE OBJECT

class JamJar:Jar{}

class PickleJar:Jar{}

class MoneyJar:Jar{}

I'd have imagined this would all be fine but the next time my code compiles or restart a session my object forgets what Type of Jar each instance within the list is, or that the instance is anything at all as I'm met with a null reference.

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?





Aucun commentaire:

Enregistrer un commentaire