SOLVED: Hoarding Gold... coin.pos error

I’ve ran into this problem in other stages as well, and somehow end up working around it eventually, but I’m getting concerned with the issue now. I’ve read the help guide and watched the tutorial video. Here is my code:

    var totalGold = 0;

loop {
    var coin = this.findNearestItem();
    coinPos = coin.pos;
    coinX = coin.pos.x;
    coinY = coin.pos.y;
    this.moveXY(coinX, coinY);

} // End of main loop

I’m getting an error on the coinPos = coin.pos; line. The error tells me to use “this.pos” instead. And it says "cannot read property of “pos” of null.

What does that mean? And what am I doing wrong?

You can’t find the pos of null. You get null when you define item. At the very start of the level, there are no coins, so this.findNearestItem() returns null. Add an if (item) { check before you define the variables.

1 Like

Ugh! I can’t believe that is all it was.

So just for the sake of understanding, could you explain that a bit more? I want to better understand. If the original code was in a loop, would it continue to run looking for coin? And then once it finds it find pos?


Here, let’s walk through your program:

// Level starts up, no coins.
var totalGold = 0 // Initializes totalGold to keep track of your gold (although you could just use
loop {
    var coin = this.findNearestItem(); // Checks for items, finds none, returns null.
    coinPos =  coin.pos; // Since coin is null, throws error "Can not read 'pos' of null."
    // Rest of your loop goes here.

When an error gets thrown, the code basically just stops running altogether. So, when you defined coinPos, it threw an error and the code stopped.

Ahh, I see! THAT makes sense. I had wondered why when the coins did appear it didnt kick into action.

Thanks so much!