Dictionary reference disappearing

Hi guys,

I’m pretty new to C#, and I’ve run into a bug thats probably an easy and simple fix but I’m just going round in circles now and can’t see the solution.

I have a class ‘Planet’ which contains another class ‘Planet_Data’ (used for serialization) which contains another class ‘Industry’. The Industry class has a Dictionary> member named ‘productionSheet’ (marked as [System.NonSerializable], constructed like so

public Industry(Storage s)
{

    productionUnits = new List<ProductionUnit>();
    ReloadDictionary();
}

public void ReloadDictionary()
{
    productionSheet = new Dictionary<Enums.Commidities, ConsumptionAndProduction>();
    foreach (Enums.Commidities e in Enum.GetValues(typeof(Enums.Commidities)))
    {
        productionSheet.Add(e, new ConsumptionAndProduction(0, 0));
    }
}

My planet object is constructed like so

void Awake()
{
    data = new Planet_data();

    // other members
    data.industry = new Industry(getStore());
    Debug.Log(data.industry.productionSheet);
    // other members
}

When the scene is launched, the productionSheet is printed out correctly to the console, ie it is instantiated and assigned to at this stage. I then have a function which is called from Update(), which looks like this

void Turn()
{
    Debug.Log(data.industry);
    data.industry.ClearProductionSheet(); //
    //

Industry::
public void ClearProductionSheet()
{
    foreach (var e in productionSheet) // null reference exception 
    {
        e.Value.consumption = 0;
        e.Value.production = 0;
    }
}

The log shows that at the start of turn, the Industry object has been instantiated. However, the Dictionary contained within is now null.

I don’t understand why my Dictionary has lost it’s reference. Again, this is probably a simple thing I’m missing, but can anyone point out the problem to me?

Because unity saves data through XML serialization. Dictionaries are not serializeable. Lists and arrays are.

So, basically, you cannot save Dictionaries. You have to convert them to arrays or lists and back when saving/loading, or just use a list/array to begin with.

If you need to store the data in the dictionary, see this question and my comment in it to get you started on the conversion.