Ghost through enemy for a short duration after being damaged

I have AI enemies that chase player and when they collide with player, player gets damage and for a short duration player does not get extra damage and I also want player to ghost through enemies while effect takes place.


Both player and enemies got Colliders on them.

Player got tag “player” and layer “player”

Enemies got tag “NPC” and layer “NPC”

“NPC” and “player” layers both collide in collision matrix.


What is the good way to achieve this ghosting effect?

The method in which this should be performed.

void Damaged(DamagePackage damagePackage)
    {
        if (tag == damagePackage.OwnerName)
        {
            return;
        }
        if (CompareTag("Player"))   
        {
            if (!(Time.time > _nextRecieveDamage)) return;
            _nextRecieveDamage = Time.time + 0.1f;
        }
        HP -= damagePackage.Damage;
    }

You can cache any collision with any type of enemy that way you can check the cache on collision to see if we have already collided with this type of enemy, if not then we apply the action we want to happen and push the enemy to the collided cache, where as a certain amount of time passes we remove it from the cache. The reason for allowing cache of multiple types of enemies is so that we can apply different effects to different kind of enemy types if we have to. Something like:

    private HashSet<int> _collissionCache = new HashSet<int>();

    void Damaged(DamagePackage damagePackage, int entityId)
    {
        if (tag == damagePackage.OwnerName)
        {
            return;
        }

        // Check if we have this entity in our cache
        if (_collissionCache.Contains(entityId))
        {
            // Check if the time is finished
            if (Time.time > _nextRecieveDamage)
            {
                // Remove from cache and continue the method.
                _collissionCache.Remove(entityId);
            }
            else
            {
                // If time is not done we add next receive damage time and return.
                if (CompareTag("Player"))
                    _nextRecieveDamage = Time.time + 0.1f;

                return;
            }
        }

        // Apply the effect
        HP -= damagePackage.Damage;

        // Add entity to cache
        _collissionCache.Add(entityId);
    }