1

Here is the code I've been trying to use to serialize a list into JSON:

void Save()
        {
            Debug.Log("Save");

            InfoSaveList saveList = new InfoSaveList();

            // this steps through information nodes and collects 
            // the information they contain
            foreach (BaseNode n in rootNode.childrenNodes)
            {
                var id = n.nodeID;
                var info = n.infoLine;

                InfoSave infoSaveData = new InfoSave();
                infoSaveData.nodeID = id;
                infoSaveData.info = info;

                saveList.infoSave.Add(infoSaveData);

            }
            string infoSaveDataToJson = JsonUtility.ToJson(saveList, true);
            Debug.Log(infoSaveDataToJson);
        }


[System.Serializable]
public class InfoSave
{
    public int nodeID;
    public string info;

}

[System.Serializable]
public class InfoSaveList
{

    [SerializeField] public List<InfoSave> infoSave;
}

for some reason I'm getting the error:

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

on the line:

saveList.infoSave.Add(infoSaveData);

I can't figure out why that would be the case, I'm trying to step through my code and it all seems to make sense to me but I'm clearly missing something.

If i get through this error, will this even save correctly as JSON? or can that only be done with arrays no lists?

1 Answer 1

2

You simply never instantiate your list.

Either do it through a constructor, when declaring the list, or from your Save function since the list is public.

// Constructor :

[System.Serializable]
public class InfoSaveList
{

    [SerializeField] public List<InfoSave> infoSave;

    public InfoSaveList()
    {
         infoSave = new List<InfoSave>();
    }
}

// Declaration :

[System.Serializable]
public class InfoSaveList
{

    [SerializeField] public List<InfoSave> infoSave = new List<InfoSave>();
}

// From Save function

void Save()
{
    // ...
    InfoSaveList saveList = new InfoSaveList();
    saveList.infoSave = new List<InfoSave>();
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm so dumb, this was it! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.