- Home /
Best practice handling deleted object refences during SceneManager.LoadScene
Hey guys,
I've been getting NPEs when I call SceneManager.LoadScene because I have objects that are referenced after they have been deleted. This is the error I get:
The object of type transform has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
I know I can just put in null checks where this is an issue, but this issue crops up EVERYWHERE. Any object that stores a reference to player transform and checks it during update hits this issue. Any object that needs a UI element reference and calls it in update hits this issue. Every action that could EVEN POTENTIALLY be called on the same frame that I call SceneManager.LoadScene can hit this issue because the objects are destroyed at random when the scene is being unloaded.
I have browsed a lot of threads and have not been able to find a clean solution to this problem. I know the go-to answer given is that I can make it a singleton or persist the referenced object across scenes, but I really want to avoid overusing singletons and DontDestroyUnload. I want each scene to be as self-contained as possible.
Does anyone know how to solve this cleanly or recommend some best practices reading? I feel like I'm missing something big because this feels like a very simple issue to fix and yet I can't think of any clean solution.
Thank you!