Search code examples
collisiondetection

Getting all enemies to attack the player inside a collider in unity 2d


I'm making a game in Unity 2D. So here's my question, If the player Triggers a collider (big area), How do I make all the enemy gameobjects inside the collider to attack the player?

I want to make it like but I don't know how to.

void OnTriggerEnter2D(Collider2D other)
    {
        //all enemies inside this collider attack the player
    }

Can someone please help me?


Solution

  • Use OverlapAreaAll to get all the enemies in an area.

        public LayerMask enemyLayerMask;
        private void OnTriggerEnter2D(Collider2D other)
        {
            Collider2D thisCollider = GetComponent<Collider2D>();
            Collider2D[] enemyColliders = Physics2D.OverlapAreaAll(thisCollider.bounds.min, thisCollider.bounds.max, enemyLayerMask);
            foreach(Collider2D enemyCol in enemyColliders)
            {
                 Enemy enemy = enemyCol.gameObject.GetComponent<Enemy>();
                 if (enemy != null)
                 {
                     enemy.AttackPlayer();
                 }
            }
        }