Character won't stop targeting dead enemy

This has happened in a few levels, the enemy is dead and the code stops. Sometimes I get the “but it’s dead” notice but not always. I tried modifying my pet process to filter by the enemy health but no change.
2020-10-28 13_31_51-Sarven Rescue

def petBattle():
    while True:
        pet.moveXY(hero.pos.x -1,hero.pos.y)
        if enemy: 
            if distance < 10 and pet.isReady("cold-blast"):
                pet.coldBlast(enemy)
        
        
pet.on("spawn", petBattle)

while True:
    enemy = hero.findNearestEnemy()
    if enemy and enemy.health > 0:
        distance = hero.distanceTo(enemy)
        if hero.isReady("flash") and distance < 10:
            hero.flash(enemy)
        if hero.canCast("chain-lightning"):
            hero.cast("chain-lightning",enemy)
        else:
            hero.attack(enemy)
    if enemy and enemy.health < 0:
        enemy = hero.findNearestEnemy()
    
    flag =  hero.findFlag("green")
    if flag:
        hero.pickUpFlag(flag)

Maybe try putting a enemy = hero.findNearestEnemy() inside this while-true loop.
Lydia

will it work to have two find enemy sections (the pets and the heroes) running at the same time?

I think so . . .
Lydia

@Manticore412, The issue is that you are not checking for an enemy inside your loop. Like @Lydia_Song said, you need to have a enemy = hero.findNearestEnemy() at the beginning of your while loop. You need this because your hero will just get stuck in a loop without ever changing targets, even if that enemy is dead. Hope this helps!
Grzmot

just so you know:

if enemy and enemy.health > 0

does the same thing as if enemy because
hero.findNearestEnemy only returns the nearest living enemy.