Trying to replace variable (var c = hero.FindNearestItem()) with just hero.FindNearestItem() and the game returns unexpected errors

The following code works fine and the coin value is counted as normal:

var c = 0;
while (true) {
var coin = hero.findNearestItem();
if ( hero.findNearestItem()) {
hero.moveXY( hero.findNearestItem().pos.x, hero.findNearestItem().pos.y);
c += coin.value ;
}
if ( hero.time >= 30) {
break;
}
}

However, changing the variable “coin” to hero.findNearestItem() (I’ve bolded the changes below) gives the wrong value OR throws up null errors.

var c = 0;
while (true) {
if ( hero.findNearestItem()) {
hero.moveXY( hero.findNearestItem().pos.x, hero.findNearestItem().pos.y);
c += hero.findNearestItem().value ;
}
if ( hero.time >= 30) {
break;
}
}

Is it a bug or is there some mistake I’m making? Please let me know.

1 Like
var c = 0;
while (true) {
if ( hero.findNearestItem()) {
hero.moveXY( hero.findNearestItem().pos.x, hero.findNearestItem().pos.y); 
c += hero.findNearestItem().value ;
}
if ( hero.time >= 30) {
break;
}
}

Probably problem is following

you place

c += hero.findNearestItem().value ;

after

hero.moveXY( hero.findNearestItem().pos.x, hero.findNearestItem().pos.y); 

so
1 you pick up item
2 you try to add value of already picked up item to the “c”
but instead you add value of next item
and if next item not exists it causes an error


2 Likes

You’re absolutely right! D’oh!

Thanks again for that simple and awesome explanation :slight_smile:

2 Likes