Home > Mobile >  Detecting Enemies inside Area,Detecting Enemies inside Circle UNITY2D
Detecting Enemies inside Area,Detecting Enemies inside Circle UNITY2D

Time:04-19

im doing my first game and im trying to detect the enemies inside an circle area around my player.

i have two problems right now:

-When a start the game, the circlecollider and player collider is detected as enemies even when i use the compare tag "Enemy"

-My corroutine dont refresh every 2s, and only detect colliders one time when the game start

public class ItemDamage : MonoBehaviour
 {
     [SerializeField] int damage;
     [SerializeField] Collider2D[] objectsInsideArea;
     Vector2 radiusOfDamage;
     int radius;
     public void Start()
     {
         radiusOfDamage = new Vector2(radius, 0f);
         StartCoroutine(DamageEnemy());
     }
  
     bool IsEnemy(string tag)
     {
         for (int i = 0; i < objectsInsideArea.Length; i  )
             if (objectsInsideArea[i].gameObject.CompareTag("Enemy"))
             {
                 Debug.Log("object {i} is an Enemy");
                 return true;
             } else
             {
                 Debug.Log("object {i}");
             }
         return false;
     }
  
     IEnumerator DamageEnemy()
     {
         objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
         foreach (bool IsEnemy in objectsInsideArea)
         {
             Debug.Log("You damage the enemy");
         }
         yield return new WaitForSeconds(2);
     }
 }

CodePudding user response:

For coroutine to repeat itself, it has to start itself in the end again like this:

IEnumerator DamageEnemy()
     {
         objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
         foreach (bool IsEnemy in objectsInsideArea)
         {
             Debug.Log("You damage the enemy");
         }
         yield return new WaitForSeconds(2);
         StartCoroutine(DamageEnemy());
     }

Also instead of coroutine for this, you can use InvokeRepeating method.

You don't have to use a predefined array of objects, but rather use SphereRaycast method where you specify layer of objects to look for. And your enemies can be located in the specific layer.

CodePudding user response:

A Caroutine does not start it self.

For the other problem. objectsInsideArea is a Collider array and not a bool array. You cannot check it this way. Your code must look like this:

IEnumerator DamageEnemy()
{
     while(someBoolOrTrue) {
          objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
          foreach (var collider in objectsInsideArea)
          {
               if(collider.tag.Equals("Enemy")) {
                    Debug.Log("You damage the enemy");
               }
          }
          yield return new WaitForSeconds(2);
    }

}
  • Related