- Home /
How to create a generic list from a group of gameObjects with specific tag?
Hello all. I am using C# in Unity, and I am importing System.Collections.Generic to use Lists. I have 12 gameObjects in my scene with the tag "Enemy". How would I go about adding these objects to my list on Awake or Start, then remove them once they are destroyed, without causing any issues?
Answer by ArkaneX · Sep 21, 2013 at 08:34 PM
Assuming you have some EnemyManager script, you can do it in the following way:
public class EnemyManager : MonoBehaviour
{
public List<GameObject> enemies;
void Start ()
{
enemies = new List<GameObject>();
foreach (var enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
var enemyScript = enemy.AddComponent<EnemyScript>();
enemyScript.enemyManager = this;
enemies.Add(enemy);
}
}
}
where EnemyScript looks like:
public class EnemyScript : MonoBehaviour
{
public EnemyManager enemyManager;
void OnDestroy()
{
enemyManager.enemies.Remove(this.gameObject);
}
}
This is a simple example, serving as a base for actual implementation. It has some flaws, for example if you destroy EnemyScript component, OnDestroy will be called as well, causing removal of actual game object from the list. But I think that modifying the above code you'll be able to implement your own solution.
Thanks, this explains how to use a generic list in the proper manner, got me where I needed to be :) +1