I’m currently developing a piece of software where the user will perform an activity to get a score, and can go back in and perform the same activity again to improve their score.
To load the activity, we simply instantiate a prefab and disable our “player” so the prefab has control.
When the user completes the activity, we destroy the prefab with Destroy, not DestroyImmediate (though I have tried this to see if it has an effect on what I’m witnessing).
My problem is that when the user goes back into the activity there seem to be some “ghost” scripts from the previous activity load that are still receiving events. When I put a breakpoint at the top of the event-receiving functions, it tells me that “this” is null, so the script itself is null. And of course I get a MissingReferenceException, presumably because the object that held the script isn’t around anymore.
I have tried to search around for an answer to why this is happening, and in my search I found someone stating that when Destroy is called, the gameObject is destroyed, but the scripts are not. Or at least they aren’t destroyed immediately. From what I understand they are supposed to be cleaned up at the end of the frame where Destroy was called, presumably to give them time to finish their Updates.
Has anyone else encountered this issue? Does anyone know of a way to be sure the scripts get destroyed? It is possible that I am just doing something horribly wrong and don’t realize it, but the problem seems pretty straightforward to me.
Thanks.
I just tested your suggestion - unsubscribing from the events in OnDestroy - and that did indeed work. So the scripts don't receive the events because they have unsubscribed, but I fear that the ghost scripts themselves may still be hanging around. I worry that memory accumulation may be an issue if these ghost scripts keep getting created and hanging around. Thank you for the workaround though - it has helped me move on in implementation at the very least. :)
– shakenYou're welcome. That's why I didn't want to post that as answer because it still doesn't take care of those ghost scripts hanging around :) Edit: Since Components can be removed with
– mhtraylorDestroy(), it might be possible to ensure the scripts are removed first by usingDestroy()on them before Destroy() on their gameObject?@mhtraylor could you convert your comment to an answer, so this question can be closed :)
– Benproductions1