Search Unity

Friendly Attacking AI, Issue With Multiple Enemy Targets

Discussion in '2D' started by shadowskullk4, Aug 19, 2020.

  1. shadowskullk4

    shadowskullk4

    Joined:
    Feb 28, 2020
    Posts:
    1
    I'm not exactly sure how to articulate this issue, but I will try my best.
    I've been stumped recently on how I should be referencing the "_target" GameObject. In my scene, I have a Friendly (The object this code is attached to) and multiple Enemy objects that are tagged as "Enemy". I want to be able to reference multiple Enemies depending on their range from the Friendly.

    What I Want To Happen:
    For example, there are two Enemies. Enemy 1 is out of range from the player, Enemy 2 is within range. The friendly object shoots at Enemy 2 and ignores Enemy 1 because it is out of range. Once either Enemy enters range, the Friendly object will Shoot at the Enemies.

    What's Happening:
    Since I'm not sure how to properly reference multiple GameObjects without iterating through an array the friendly only does distance detection for the first Enemy object found in the scene. No matter how many Enemies are located in the scene, the friendly AI will still prefer to shoot the first Enemy found with the tag "Enemy".

    Simply put, I just need a way to reference multiple Enemies.

    Code (CSharp):
    1.  private void CheckDistance()
    2.     {
    3.         _target = GameObject.FindGameObjectWithTag("Enemy");
    4.         _distanceToEnemy = Vector2.Distance(_target.transform.position, transform.position);
    5.         if(_distanceToEnemy <= _detectionDistance)
    6.         {
    7.             print("enemy is within range");
    8.             AttackEnemy();
    9.         }
    10.     }
    11.