What is the best code pattern to use when keeping references to Unity GameObject
s that may be Destroy
ed elsewhere in the code?
I’ve read that you should always destroy a GameObject
then set any references to null at the same time but the problem is that a class may have a reference to a GameObject
and be unaware that is has been destroyed.
The equality operator for a GameObject
is overridden so that a Destroy
ed GameObject
will return true when compared to null
, but it is a bit cumbersome when iterating through a collection of GameObject
s since it doesn’t seem possible to remove the deleted objects easily.
An example scenario: Whenever a Enemy
with a collider comes into range of the player and causes OnTriggerEnter
to be called on the player object, the player object keeps a reference to the Enemy
to know how many Enemies are nearby so it doesn’t have to query the world every time it needs to perform some sort of logic involving them.
The problem is that one of these Enemies may have been Destroyed (by another player perhaps) which means the Enemy GameObject in the collection held by the player is now null.
It does not seem that it is possible to filter them out using an approach like this:
ArrayList deletedObjects = new ArrayList();
foreach (GameObject enemy in enemiesInRange)
{
if (enemy == null)
{
deletedObjects.Add(gameObject);
}
}
foreach (GameObject deleted in deletedObjects)
{
enemiesInRange.Remove(deleted);
}
C Sharp has WeakReference and maybe that could be used to implement something like .net - Is there a way to do a WeakList or WeakCollection (like WeakReference) in CLR? - Stack Overflow but it seems cumbersome compared to other languages.
I feel like I am missing something obvious. Any help is appreciated!