Search code examples
memoryscreeps

How do I store class variables in memory?


I read a few other questions here about it but I'm just not getting it.

I have some variables that change through the course of execution so I understand that they need to go in memory.

var populationManager = {

    init: function(){
        Memory.PopulationManager = {};
        Memory.PopulationManager.nHarvesters = 0;
        Memory.PopulationManager.nUpgraders = 0;
        Memory.PopulationManager.nBuilders = 0;

        Memory.PopulationManager.harvesterNameNum = 0;
        Memory.PopulationManager.upgraderNameNum = 0;
        Memory.PopulationManager.builderNameNum = 0;
    },

    demographics: function(){
         if( ! Memory.PopulationManager.nHarvesters )
             this.init(); //not initialized yet

But it is telling me it cannot read property nHarvesters of undefined.

How do I make my own screeps Memory objects and use them?


Solution

  • After looking over your code I found that the issue is that you are checking for a property of an object that doesn't exist and want you should be doing is checking if the actual object exists.

    Change

    if( ! Memory.PopulationManager.nHarvesters )

    to

    if( ! Memory.PopulationManager )

    and that will do what you need it to.