- Home /
Question by
Viridiel · Dec 19, 2014 at 10:54 PM ·
generic list
Missing(GameObject) in Generic List (C# Unity3D)
'ello. I have a problem with the Generic List in Unity. I've made a List out of GameObjects where I add enemies if they're in range. If the enemy dies, they should destroy theirself and remove them out of the list. I don't know why, but when I run my game and shoot an enemy I will get the following error: "MissingReferenceException: The Object of type 'Gameobject' has been destroyed but you're still trying to access it.", And the first item in my list says "Missing(GameObject)" I've read alot of questions here and every-one says the same that you need to remove them out of the list, but I'm doing so and I still get the error.
Here is my script:
public void DestroyEnemy(GameObject enemy)
{
bool _finished = RemoveFromList(enemy);
if (_finished)
{
Destroy(enemy);
}
}
bool RemoveFromList(GameObject enemy)
{
bool destroyed = false;
foreach (GameObject tower in GameObject.FindGameObjectsWithTag("Structure"))
{
List<GameObject> enemiesInRange = tower.GetComponent<Structure>().enemiesInRange;
if(enemiesInRange.Contains(enemy))
{
enemiesInRange.RemoveAt(enemiesInRange.IndexOf(enemy));
destroyed = true;
}
}
return destroyed;
}
Comment