Declaration of variables overwrites my Dictionary initialized on Reset() callback

Output of StatList.Count is 0 even though I inserted 3 objects at the Reset() callback. I can only assume that the code below “Runs 2nd” comment overwrites the code below “Runs 1st” comment. Help is greatly appreciated!

Goal is to see the Dictionary at the Inspector before we hit Play, so placing the initialization on Start() is out of the question

public class Stats : MonoBehaviour
{
    //Runs 2nd (Overwrites the initialization done in Reset())
    public Dictionary<StatType, int> StatList = new Dictionary<StatType, int>();

    //Runs 1st (Initializes the List)
    private void Reset()
    {
        StatList.Add(StatType.PhysicalPower, 1);
        StatList.Add(StatType.MagicalPower, 1);
        StatList.Add(StatType.Speed, 1);
    }

    //Runs 3rd (No changes on the List since "Run 2nd")
    private void Start()
    {
        //Output is 0s
        Debug.Log(StatList.Count);
    }
}

public enum StatType
{
    PhysicalPower,
    MagicalPower,
    Speed,
}

The field would get initialized before Reset is called, as field initialization is performed during construction time (before which there would be no object to call Reset on). This means that your “Runs 1st” and “Runs 2nd” comments should actually be swapped.

The dictionary values are getting cleared on run because Unity serialization doesn’t support Dictionary types out of the box. There’s many topics on this issue, here’s one.

2 Likes

Thank you!