After defender is destroyed, I don't understand how the attacker starts walking again

I understand that we would want to set the isAttacking Boolean to false in the animator if we can’t find the current target - and I did it as part of the challenge thinking it would only be a part of the solution - but it works fully and I don’t understand why.

in Attacker.cs:

    if (!currentTarget)
        anim.SetBool("isAttacking", false);

and also (which called from Lizard.cs in OnCollisionEnter2D) :

// On start of attack, detemrine what we are attacking
public void Attack(GameObject obj)
    currentTarget = obj;
    currentTargetHealth = obj.GetComponent<Health>();

The problem I have is that there isn’t anywhere that re-initialises the ‘currentTarget’… I mean if when the lizard enters the defender’s collisionbox, the onCollisionEnter2D executes, and calls Attack, where currentTarget gets set,

There isn’t any kind of “OnCollisionExit” to reset the currentTarget - so surely, when the target gets destroyed, the currentTarget variable is still set to the (now destroyed) object?

But it does work - and I don’t understand why.

Is it because the destroyed object becomes null? and therefore currentTarget becomes null?

I would imagine that’s the case, yes. Try logging out currentTarget in your update function

currentTarget is set to a specific GameObject and that GameObject has been destroyed, so the reference should no longer have anything to point to and will likely therefore be null.

Privacy & Terms