Optimization

Hi, I just started unity. I’m making a level intelligence test game. There is a prefab keypad object that exists in every scene. As the level progresses, RAM swells due to these prefabs and the game shuts down. Every time I go to a new level, I have to destroy the previously created prefab, how do I do it.

Some questions:

  • Is the prefab spawned in each scene at runtime?
  • Can/Should there be multiple instances of this prefab spawned in each level?
  • Is the prefab marked with DontDestroyOnLoad?

If there’s supposed to be only one instance of this prefab in a scene and it is not marked with DontDestroyOnLoad, then changing scenes will automatically destroy it, removing it from memory.
In this case, its possible that you have a script on your prefab that’s creating a memory leak.

If there’s supposed to be only one instance of this prefab in a scene and it is marked with DontDestroyOnLoad, then either remove DontDestroyOnLoad from it, or remove the other prefab instances from each other scene, and re-use one instance across all scenes.

If multiple instances of this prefab are spawned at runtime and they are not marked with DontDestroyOnLoad, then check to make sure whatever you’re using to spawn this prefab isn’t endlessly creating new instances. Changing scenes will still destroy all instances & remove them from memory regardless.

If multiple instances of this prefab are spawned at runtime and they are marked with DontDestroyOnLoad,
then that kind of sounds like a bad idea altogether.

Actually yes. I used DontDestroyOnload. But I used this command for something unrelated, does it still work? For example, these prefabs are buttons, and inside these buttons, there is a button sound that works with every touch. This button voice prefab. This button sound prefab has DontDestroyOnload. But this DontDestroyOnload only works when those buttons are pressed, when the scene changes without those buttons being touched, does it still work.

use the memory profiler to confirm the cause of the memory leak

I am doing sqlite query in this prefab. Could this be a reason for not being erased from RAM

That could explain why the memory usage, particularly Managed Heap Memory (Used and/or Reserved), grows. But If you mean the GameObject not getting destroyed I don’t thinks so (unless whatever script or asset store solution you have is triggering DontDestroyOnLoad) but

If you mean you use
DontDestroyOnload on a different component on the same GameObject, then yes, that will keep the entire GameObject around between scene loads.

Have you taken two memory snapshots with the Memory Profiler package and investigated the diff between them?

Hello Martin. Thank you for your answer. But I found the problem. The problem is google video ad. I have a prefab that is in every scene and there is a video ad script in this prefab and it does upload and event listening in every scene. I found the solution for this by making the ad script singleton

1 Like