Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Get number of objects with a tag and have a bool script?

Discussion in 'Editor & General Support' started by brolol404, Oct 31, 2020.

  1. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    I am trying to get the number of objects tagged as enemies that are also archers. Archers are set by a bool on a script on the game object. How would I do this?

    int UnitCountArcherEnemy = GameObject.FindGameObjectsWithTag("Enemy").Length; (only count the objects that have GetComponent<UnitClass>().archer set to true)
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,495
    Code (CSharp):
    1. int archerCount = 0;
    2. GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
    3. foreach (GameObject enemy in enemies)
    4. {
    5.   if (enemy.GetComponent<UnitClass>().archer) archerCount++;
    6. }
    7. Debug.Log("There were " + archerCount + " archers found.");
     
    brolol404 likes this.
  3. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    awesome! thanks so much!
     
    adamgolden likes this.
  4. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    An interface sounds like it would be useful here.
    Whichever enemies you have that are supposed to be archers, you could give them an
    IArcher
    interface that contains archer-specific properties.

    Then you'd only need to do this to find the number of archers in the scene:
    Code (CSharp):
    1. FindObjectsOfType<IArcher>().Length;
    Same could be done with different types of enemies as well.
     
    adamgolden likes this.
  5. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    Thanks! I will look into this!