Use FindGameObjectsWithTag for a list

Hi. I’m trying to make a list containing all the enemies in a level so I can tell them when to attack, so they don’t just all punch at the same time. How do I use FindGameObjectsWithTag in a list instead of an array?

The best you can do is not to use tags and not to use FindGameObject***. How about this: Whenever the Enemy script is enabled, it adds itself to a HashSet of all enemies in the scene. Whenever it’s disabled, it removes itself from the HashSet. That way, you always have an up-to-date collection of enabled enemies.
HashSet instead of List, because it’s more efficient at removing objects and testing whether an object is in the set.


class Enemy : MonoBehaviour 
{     
    void OnEnable()
    {
          FindObjectOfType<EnemyManager>().AddEnemy();
    }

    void OnDisable()
   {
         FindObjectOfType<EnemyManager>().RemoveEnemy()
   } 
} 


using System.Collections.Generic; 
class EnemyManager : MonoBehaviour
{
     private readonly HashSet<Enemy> m_enemies = new();
     public void AddEnemy(Enemy enemy) => m_enemies.Add(enemy);
     public void RemoveEnemy(Enemy enemy) => m_enemies.Remove(enemy);
}

If you’re gonna use GameObject.FindGameObjectsWithTag

Then what you can do is this:
List<GameObject> gameobjects = GameObject.FindGameObjectsWithTag("TagExample").ToList();

And on top of your code you have to place this line of code:
using System.Linq;