- Home /
List or Array of Custom Classes not saving into prefabs properly?
I have a class defined inside a component. It's more or less just a struct of raw data:, i.e.
[ExecuteInEditMode]
class ListOfData : MonoBehavior
{
public class DataElement
{
public float stuff;
public GameObject thing;
//etc.
}
List<DataElement> mListOfDatas;
void Update()
{
if (!Application.isPlaying)
{
mListOfDatas = mListOfDatas ?? new List<DataElement>();
}
}
}
I also have an editor script, changing the contents of mListOfDatas. Unfortunately, this data is not showing up in the component UI, and i'm guessing that only stuff shown in the UI will actually save. Is this the case, and is there a way to force this data to save to the prefab, or force it to display?
I think I'm getting to the limits of the prefab system, here.
Answer by Bunny83 · Jul 18, 2011 at 02:58 PM
First, only public variables or private variables with SerializeField attribute are serialized. Also you can only serialize arrays or lists of serializeable types. You can turn your DataElement class into a serialized type by adding the Serializable attribute
class ListOfData : MonoBehavior
{
[System.Serializable]
public class DataElement
{
public float stuff;
public GameObject thing;
//etc.
}
[SerializeField]
List<DataElement> mListOfDatas;
I lied! It only seems to store the first element when I close and re-open. And sometimes forgets normal, "public" stuff. Does using [SerializeField] once mean I have to start using it everywhere in that class?
I have a question about this code. How to serialize list of class or struct from another script?
This question was about unity's serialization system which can only serialize things inside the editor. If you have a different question, please ask a question and don't wake a 4+ years old thread. Also your one-liner you've posted is barely enough to actually understand what you want to do.
Ask a seperate question. You can include a link to this question / answer for reference, but make sure you describe your question in a way it can be understood. Example code would help, even when it's pseudocode.
Answer by Molix · Jul 18, 2011 at 02:59 PM
Add [Serializable] before your custom class declaration. Then the public members will be saved/editable like the ones in your MonoBehaviour.
i.e.
[Serializable]
public class DataElement
{
...