[Solved] why do I get 'null' here?

This one below is a something I did for the Airdrop map of Backwood Forsest.
Actually, the goal of the map is not relavent.
I was stuck with a problem with function.

# Get all swords and protect the village.

def onSpawn (event):
    while True:
        item = hero.findNearestItem()
        #  The pet should fetch the item if it exists:
        if item:
            pet.fetch(item)

# Assign onSpawn function for the pet's "spawn".
pet.on("spawn", onSpawn)

def heroVigil():
    while True:
        enemy = hero.findNearestEnemy()
        enemyD = hero.distanceTo(enemy)
        if enemyD < 5:
            if hero.isReady("cleave"):
                hero.cleave(enemy)
            else: 
                hero.attack(enemy)
        else:
            hero.shield()
        
            

while True:
    # Guard the left passage: 
    hero.moveXY(22, 34)
    heroVigil()
    pass

I got a warning message: “Line 16: ArgumentError: distanceTo’s argument target should have type object, but got null. distanceTo target is null. Does the target exist? (Use if?)”

Why does enemyD get ‘null’ value? Is it because the ‘enemy’ in the ‘def function()’, ins’t explicitely(?) defined as a variable? If so, does it mean that you can’t write more than one variable inside a function when you define it?

The weird thing is that my hero did all the proper things I intended. She used ‘cleaves’, attack, and sheild herself.

I solved it by putting

if enemy:

between those two below.

   enemy = hero.findNearestEnemy()
   enemyD = hero.distanceTo(enemy)

It was kinda the same thing as the one I asked a day ago here. Sorry for the trouble :smiley:

Good to see you are catching the little things on your own. Coding is a lot of little details that need to be arranged just right to make it work correctly. Little by little your understanding grows and the little details come easier to piece together.

Just keep trying and learning. :grinning:

1 Like

Thank you very much :smiley: :smiley: :smiley: :smiley: :smiley: