Shooting at a target on with a dead enemy in the path yields a bug

Hi Rick, thanks for all the great videos. One thing I noticed with your solution to the OnTriggerEnter code was, that you’re only checking whether the TARGET is dead, and not the Health component of the game object we collided with, so if my arrow has to pass over a dead monster to hit my target, it will disappear when it enters the dead monsters collider… Here is my solution…

        private void OnTriggerEnter(Collider other)
        {
            var otherHealth = other.GetComponent<Health>();
            if (otherHealth == null || otherHealth.IsDead) return;
            
            otherHealth.TakeDamage(_damage);
            Destroy(gameObject);
        }

Good tip. Be careful, though, because this logic can allow your arrows to fly right through buildings and trees as well.

1 Like

Hey Welcome DrDisappointment and thanks for sharing your findings :slight_smile:

1 Like

I absolutely expect it’ll fly through everything and anything. Initially I blamed my character’s sheer brute force, but then discovered it was just an apparent issue which I imagine will be solved in a later lecture! :grin:

Not sure, but i personally always feel like just disabling colliders on dead stuff works well, then it cant mess with anything anymore.
Unless you dont like the playing being able to walk through the corpses ofc.

2 Likes

I had already added disabling the collider if some enemy died:

//Health.cs
    private void Die()
    {
         //...
         GetComponent<Collider>().enabled = false;
        //
    }

Now I’ve got this

// Projectile.cs
        private void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.GetComponent<Terrain>()) Destroy(gameObject);

            if (target != other.gameObject.GetComponent<Health>()) return;

            if (target.IsDead()) return;

            hasHit = true;
            target.TakeDamage(damage);

            transform.SetParent(targetRootBone);    // Re-parent to make the arrow get stuck on the target
            Destroy(gameObject, destroyDelay);
    }

The first check will catch all projectiles that leave the game’s area (unless I made some mistake with surrounding the edge of the terrain, that is).
If what was hit isn’t the target then return. This should probably be changed to allow hitting any object having Health

In case some hit was registered, the projectile deals its damage and then stays in the target for a set amount of time…

Yes, in my own version, I damage the first thing it hits with a Health component. I don’t care if it hits the target, I care that when it hits a health, the health takes the damage.

if(other.gameObject.TryGetComponent(out Health health) && !health.IsDead())
{
    health.TakeDamage(damage);
    //any other fun things you want to do.  You'll have to find targetrootbone on the Health's structure
}

Privacy & Terms