// A bit on Unity 3D null handling アキタ━━━(#゚Д゚)━━━!!!!
// cached references to items needing refresh; items implementing IRefreshable all derived from MonoBehaviour
static List<IRefreshable> refreshListeners = new List<IRefreshable>();
//...
public void OnClick() {
AnalyzeItemHelper.Analyze(item); // do some logic
for(int i=0; i<refreshListeners.Count; i++) { // ...and notify listeners about change
if(refreshListeners[i] != null) { // ensure listeners didn't forget to deregister themselves
// the problem is we actually reach that line even if SomeListener listener == null
refreshListeners[i].Refresh();
} else Debug.LogWarning("One of the refresh listeners is null!");
}
}
//---- IRefreshable.Refresh implementation of one of the listeners
void Refresh {
if(this == null) return; // without this line it goes further and further, and finally throws MissingReferenceException in some random place...
itemsView.Refresh();
// ...
}
/*
the problem is caused by the fact UnityEngine.Object overrides equality operators, so if the underlying C object no longer exists (e.g. was destroyed explicitly, or the scene was unloaded) the someUnityObject == null comparison returns true.
But in this code I relied on interfaces, since there was a lot of different things that needed to be notified that given item was analyzed. IRefreshable does not override equality operators, so for the check refreshListeners[i] was not null...
all hail unity ー_ー;
*/
Comments