creep.harvest fails when used with Source from memory



  • function do_harvester(creep) {
    
        var sources = creep.room.find(FIND_SOURCES);
    
        if (creep.memory.source === undefined) {
    
            creep.memory.source = sources[0];
            return;
        }
    
        if(creep.energy < creep.energyCapacity) {
    
            // this line works fine
            creep.moveTo(creep.memory.source);
    
            // CRASH!
            creep.harvest(creep.memory.source);
        }
    
        // do more stuff here
    }
    

    This causes an error message in the console:

    TypeError: undefined is not a function
        at Creep.harvest (/opt/engine/dist/game/creeps.js:186:21)
        at Object.module.exports [as behaviour] (harvester:37:9)
        at main:124:11
    

  • Dev Team

    This happens because you can only store JSON data in Memory. Live game objects can not be stored directly. Instead, you should store their id and retrieve the game object using Game.getObjectById method:

    function do_harvester(creep) {
    
        var sources = creep.room.find(FIND_SOURCES);
    
        if (creep.memory.sourceId === undefined) {
            creep.memory.sourceId = sources[0].id;
            return;
        }
    
        var source = Game.getObjectById(creep.memory.sourceId);
    
        if(creep.energy < creep.energyCapacity) {
            creep.moveTo(source);
            creep.harvest(source);
        }
    }