Make enemies chase you when you hit them with a projectile

To make enemy chase me when i hit them with my projectile i set weapon range equal to enemies chasedistance when projectile hits them. It works fine but i get an object reference not set to an instance of an object error.
In my projectile script i added this code:

float weaponRange = player.GetComponent(Fighter)().GetRange();
other.GetComponent(AIController)().SetChaseDistance(weaponRange);

it points to the second line.

in the fighter script i added a function to get the range:

public float GetRange()
        {
            return currentWeapon.GetRange();
        }

in the aicontroller script i added this function to set the chasedistance:

public void SetChaseDistance(float weaponRange)
        {
            chaseDistance = weaponRange;
        }

any idea whats going on here?

You’re not doing any null checks. It could be any object that’s null.

I’d start with the script and line that mentioned the error.

ok thnx that solved the problem when i checked if AIController could be null.

Without the complete OnTriggerEnter, it’s hard to tell what’s properly set and what’s not… but an other.GetComponent should always be null checked…

I’m assuming that the player is the shooting object (don’t forget your enemies will shoot too!)…

Let’s do a little null checking using a newer method called TryGetComponent

if(other.TryGetComponent(out AIController aiController)
{
    float weaponRange = player.GetComponent<Fighter>().GetRange();
    aiController.SetChaseDistance(weaponRange);
}

Note that we don’t need to do a null check on the “player” (could be enemy) fighter component because the Fighter component is what fired the projectile in the first place.

What this does is first check to see if there is an aiController on the “other” object. If there is, then the code inside the block is executed, and aiController is guaranteed to be not null within that code block.

Please note that in a later lecture, we’re going to learn a much better way of drawing aggro with our ranged weapons.

thnx ill try this, this seems to solve the problem in a cleaner way :slight_smile:

Privacy & Terms