Remove from List, how to now what list?

Hi.
I`m instantiating enemies with my script.
I want to do it like classic arcade shooters.
You instantiate 10 enemies, and if you kill all you got an special reward.
I create a list and instantiate each one and use list.add.
Anytime my gameobject dead, i have to tell the creator and say list.remove(this)?
Thank you for support and apologize about my english.

Each enemy should have some form of unique identifier, whether you append a number or a string etc, is up to you.
When that object is to be removed, search the list for the property that matches the one provided, and remove it.

1 Like

Why would you do that? List has a Remove method that takes the thing you want removed from the list.
https://msdn.microsoft.com/en-us/library/cd666k3e(v=vs.110).aspx

2 Likes

And every time maybe i should create a list with diferent name, then instantiate the enemie and send it the list string ? and when enemie dies say “remove from this list”

I`m reading your link but i dont know what method you say.

I don’t understand your question. The link I posted is the documentation for the Remove method in List which removes the given item from the list if it exists. If you need to remove “dead” enemies then you can use the OnDestroy method in MonoBehaviour to call the remove. Unity - Scripting API: MonoBehaviour.OnDestroy()

Well, i now how to remove an item from list.
But i want to generate some list, no only one, and when an enemie dies, tell the creator and say remove it from X list.
Maybe, i have to pass to each enemie the list from where is?

Sure.

You could also use a dictionary of lists where the key is the name of the enemy.

// on some class - call it EnemyManager or something
Dictionary<string, List<GameObject>> enemies;
public void Add(string enemyName, GameObject instance)
{
    List<GameObject> enemyList;
    if (enemies.TryGetValue(enemyName, out enemyList)
    {
        enemyList.Add(instance);
    }
    else
    {
         enemyList = new List<GameObject>();
         enemyList.Add(instance);
         enemies[enemyName] = enemyList;
    }
}

public void Remove(string enemyName, GameObject instance)
{
    List<GameObject> enemyList;
    if (enemies.TryGetValue(enemyName, out enemyList))
    {
        enemyList.Remove(instance);
        if (enemyList.Count == 0)
            enemies.Remove(enemyName);
    }
}

public class Enemy : MonoBehaviour
{
    [SerializeField]
    string enemyName;

    void Start()
    {
        EnemyManager.Add(enemyName, gameObject);
    }

    void OnDestroy()
    {
        EnemyManager.Remove(enemyName, gameObject);
    }
}
1 Like

Thank you, i will try it.