when a gameobject is removed from game by calling Destroy(), the abstract data types(etc List, Stack, Queue)instances still hold the reference of the destroyed gameobject. In this case, the null reference exception will be thrown.
So, is it possible, that the destroyed gameobject can be automatically removed from any ADT instances that contain it?
Thanks in advance!
One solution, if you’re using C#, is to have the GameObject fire off an event during OnDestroy() to whatever script holds that reference in a List, Stack, etc.
public delegate void GameObjectDestroyed(GameObject go);
public class SomeClass
{
public event GameObjectDestroyed OnWasDestroyed;
void OnDestroy()
{
if (OnWasDestroyed != null)
OnWasDestroyed(gameObject);
}
}
public class AnotherClass
{
List<GameObject> gos = new List<GameObject>();
void Awake()
{
//add some gameobjects to the list and subscribe to their OnWasDestroyed events
}
void HandleGameObjectOnWasDestoyed(GameObject go)
{
if (gos.Contains(go))
gos.Remove(go);
}
}