ScriptableObjects using List when creating an asset file

Hi, I am working on my first editor class project. Im have a class that that can be created as many times as needed, each time it gets added to a list. If you click play on the editor you lose the information or if you close unity down also you lose the information. I wanted to make it so u can create a asset that stores that information so u can come back to it at any time. The way i came across is by using ScriptableObject and then creating an asset out of it. This works great for me as long as im only using Unity types like int or float. What i need is to use a List of class objects. Heres an example!

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class StoredData : ScriptableObject{
        public List<Element> Elements;
    }
    
    public class Element{
    	public int foo1;
    	public int foo2;
    
    	public Element(int _foo1, int _foo2){
    	     foo1 = _foo1;
             foo2 = _foo2;
    	}
    }

Ive made my Element class more simple so its easier to understand.

So in the editor script it has a list of Elements and a function to create the asset.

	private void StoreData(List<Element> Elements){
	    StoredData storedData = (StoredData)ScriptableObject.CreateInstance("StoredData");
	    AssetDatabase.CreateAsset(storedData, "Assets/storeddata.asset");
		
	    EditorUtility.SetDirty(storedData);

		storedData.Elements = Elements;
	}

So as a test i created a test script

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class test1 : MonoBehaviour {
	public StoredData storedData; 

	void Start () {
		print(storedData.Elements[0].name);
	}
}

This causes the error:

NullReferenceException: Object reference not set to an instance of an object

Just in case i didn’t make the question clear, How do i create an asset that stores my List Elements?

Thanks in advance, Harry.

1 Answer

1

When Unity serializes a ScriptableObject the same rules apply for custom data classes. They have to be marked as Serializable or they aren’t serialized.

So define your Element class like this:

[Serializable]
public class Element
{
    /* ... */
}

Thank you so much!