So I have an interface, IHasContextMenu. I attach that to some scripts that attach to gameobjects, and that provides methods that allow right-click popup menus when those objects are right-clicked.
Recently, I made some changes to some prefabs where those scripts are added to some gameobjects dynamically. Gameobject is instantiated from a prefab, placed in an object pool, and when it’s needed, it’s given out. The correct ItemTypeScript is applied (which has the IHasContextMenu interface) and all is well.
Problem: When that object is released, and the ItemTypeScript is destroyed, the script that handles the context menu, which caches the IHasContextMenu reference to the script stops working right.
Did some research. Unity objects which are Destroyed will still return false if tested for == null. Ok, got it. Website I found said that instead of testing == null, just using the object itself returns a bool, so you can test something like:
Destroy(scriptRef);
if(scriptRef == null) {
// This will NOT run, if the scriptRef has been Destroyed. testing == null will eval false because weird Unity stuff
}
if(!scriptRef) {
// THIS will correctly evaluate, as Unity gameobjects have overloads for this
}
The problem I’m facing is I’m not using a reference to a SCRIPT. I’m using a reference to an INTERFACE. The interface resides on quite a few different scripts, so caching the reference to IHasContextMenu and just calling contextMenuRef.menuItems works great.
Except that once that reference is Destroy’ed, testing == null results in false. And apparently, I can NOT do a boolean if(!contextMenuRef) because that’s not a built in overload.
So if a cached reference to an interface is Destroyed, I can’t find a way to test for that. Yes, I COULD make sure the destroying script also sets the reference to null, but that is a LOT of extra code in a lot of places.
Is there a decent solution for this? The best I could think of was checking if GetComponent() returned anything, but that seems excessive.