Getting NullPointerException on the target

When I attack the enemy but walk away just before the Hit() event gets triggered, I get a null pointer exception. Additionally my player continues to walk away even though he’s still in the attacking animation.

Is this supposed to be happening?


image
image

1 Like

The problem here is that when you walk away, there is a small bit of blending from the attack animation to the walk animation. If it’s close enough to the Hit() event, then it will fire. Unfortunately, at this point, you’ve already set target to null.
The solution? Check to make sure that target is not null before proceeding in Hit

private void Hit()
{
     if(target==null) return;
     Health healthComponent = target.GetComponent<Health>();
     healthComponent.TakeDamage(weaponDamage);
}
3 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms