- Home /
adding GameObjects to a list
I'm trying to add unique GameObjects to a list, for example, each time I collide with an object, I add it to the list, but if I collide with that same object, I do not want to add it to the list again. I have the following:
addEnemy.cs
if (col.gameObject.tag == "NPC")
{
enemyDatabase.addEnemy(col.gameObject);
}
enemyDatabase.cs
public List<GameObject> enemies = new List<GameObject>();
public void addEnemy(GameObject currentEnemy)
{
Debug.Log("outside");
foreach (GameObject enemy in enemies)
{
Debug.Log("checking");
if (currentEnemy.name == enemy.name)
{
Debug.Log("Already in database");
}
else
{
enemies.Add(currentEnemy);
}
}
}
if i remove the foreach and just add to the database, it works, only the same enemy is added to the database multiple times, I'm assuming the foreach does not run as there are no GameObjects inside of it at the beginning.
Does anyone know a way I can get around this?
You could just try adding a quick check before the foreach to check that there are objects within the list e.g.:
if(enemies.Count == 0)
{
enemies.Add(currentEnemy);
return;
}
That should fix it. There might be a more elegant solution that somebody posts though :)
EDIT: Although, if you have multiple copies of your enemies, that doesn't look like it would work. Once you collide with one enemy type/name, all enemies with that name would have no effect anymore.
@Neamtzu also has a more elegant solution which will remove the need for my fix. So mark their solution as the answer over me. It's just cleaner code :P
@Sospitas sometimes the most simple things go over my head :P That works great, thanks, ill select that as the answer if you convert it to a question :)
Can we destroy the complete list at once using destroy(enemies);
or do we need to use foreach (GameObject enemy in enemies){destroy(enemy)}
; ?
,Can we destroy the complete list at once or do we need to use foreach (...) for every gameObject in that list?
Answer by Neamtzu · Feb 20, 2015 at 05:03 PM
Try this:
void addEnemy(GameObject currentEnemy) {
if(!enemies.Contains(currentEnemy))
enemies.Add(currentEnemy);
}
oh jeez i totally forgott about .contains.. i used a for loop to check for every enemy in the list and when removing and adding them again i got a strange out of range error, even thought the list is 0 and i just wanted to add the enemy again after he was removed.
anyway, thanks.
Your answer

Follow this Question
Related Questions
Can't retrieve information from GameObject 2 Answers
store a gameobject ? 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Callback function cannot change game object status,callback function cannot change gameobject status 0 Answers
Help on making a Database. 0 Answers