[ad_1]
One of the simplest ways that I got here up with is, in line with the observer sample, to inform all lessons the place the thing was saved about its destruction and take away references to it from there.
That is what I at all times do.
[System.Serializable] public class DestroyableEvent : UnityEvent<Destroyable> {}
public class Destroyable : MonoBehaviour {
[SerializeField] non-public DestroyableEvent destroyedEvent = new DestroyableEvent();
public DestroyableEvent DestroyedEvent => destroyedEvent;
void OnDestroy() {
destroyedEvent.Invoke(this);
}
}
Then in another class you might have one thing like this:
[SerializeField] non-public Destroyable prefab;
non-public Record<Destroyable> objects = new Record<Destroyable>();
public void SpawnObject() {
var newObject = Instantiate(prefab);
newObject.DestroyedEvent.AddListener(objects.Take away);
objects.Add(newObject);
}
If objects are created and destroyed incessantly, it is best to use a pooling system as an alternative, however you continue to want occasions to trace when an object is returned to the pool so you’ll be able to take away it from any related lists.
One other resolution you should utilize is to periodically scan lists for null entries and take away them, or take away them if you attempt to entry an entry within the record and decide that it is null. I favor to make use of an event-driven method as proven above.
[ad_2]