Items not saving because of NullReferenceException

Hi! I might have to apologize for the dumb question but I don’t really understand why I get this error. Every time I load a shop in my game it gives me an error:

NullReferenceException: Object reference not set to an instance of an object
ShopController.IsItemBought (SpellPattern spell) (at Assets/Scripts/Unity/ShopController.cs:13)
ShopItem.Start () (at Assets/Scripts/Unity/ShopItem.cs:43)

here’s ShopController.cs

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

public class ShopController : PSingleton<ShopController>
{
    private List<SpellPattern> m_boughtSpells = new List<SpellPattern>();

    public bool IsItemBought(SpellPattern spell)
    {
        foreach(var el in m_boughtSpells)
        {
            if (el.Equals(spell))
            {
                return true;
            }
        }

        return false;
    }

    public void AddNewBoughtItem(SpellPattern item)
    {
        if (!m_boughtSpells.Contains(item))
        {
            m_boughtSpells.Add(item);
            GameManager.Instance.SaveGame();
            GameManager.Instance.LoadGame();
        }
    }

    protected override void Load()
    {
        m_boughtSpells = gameData.boughtSpells;
    }

    protected override void Save()
    {
        gameData.boughtSpells = m_boughtSpells;
    }
}

and here’s start void from ShopItem.cs

  private void Start()
    {
        anim = tutorialPointer.GetComponent<Animation>();

        isBought = ShopController.Instance.IsItemBought(spellPattern);
    }

Looks like the element you are getting from the “foreach” is null. Which probably is because either you are adding a null element in “AddNewBoughtItem” or your saving/loading system is messing with it.

Yep. You really should be checking for null items in the AddNewBoughtItem, Save and Load methods to catch any nulls slipping into the collection as soon as possible.

public void AddNewBoughtItem([NotNull]SpellPattern item)
{
    if(item == null)
    {
        throw new ArgumentNullException("AddNewBoughtItem called with a null item!");
    }
    ...
}

protected override void Load()
{
    m_boughtSpells = gameData.boughtSpells.RemoveNullValues("Bought Spells contained a null item after loading.");
}

protected override void Save()
{
    gameData.boughtSpells = m_boughtSpells.RemoveNullValues("Bought Spells contained a null item when saving.");
}

public static class ListExtensions
{
    public static void RemoveNullValues<T>([NotNull]this List<T> list, string errorIfNullFound) where T : class
    {
        for(int n = list.Count - 1; n >= 0; n--)
        {
            if(list[n] == null)
            {
                Debug.LogError(errorIfNullFound);
                list.RemoveAt(n);
            }
        }
    }
}