Detonator -- Memory Leak

  1. I found a memory leak in DetonatorBurstEmitter.cs (within Detonator freeware from Unity website). In the Awake() method, the material on a ParticleRenderer was getting assigned to reference a statically declared material within the Detonator system. It was this assignment that was causing the leak. I have assumed that when a ParticleRenderer is added as a component to a game object, that a default material is first assigned to the renderer. Then upon reassignment, the initial “default” is leaked since it is no longer referenced by the ParticleRenderer at Destroy time. To solve this, I made a call to DestroyImmediate(_particleRenderer.material) prior to the re-assignment. Furthermore, I added an OnDestroy() method to the DetonatorBurstEmitter to make sure the material assigned to the particle renderer was destroyed along with the game object at destroy time. This worked to solve the problem, but in reading the on-line unity script reference, it highly recommends using Destroy() instead of DestroyImmediate(). So here are the questions:
    a. What are the dangers of calling DestroyImmediate()? It looks like I would have to use this method instead of just Destroy() because destroy only takes action on the next frame. Since I’m making the new material assignment within the same Awake() call of this Monobehavior, it seems as if I must destroy the currently existing material immediately.
    b. Was it the right thing to do in this situation? If not, what is the recommended solution.

a. DestroyImmediate can actually permanently destroy your assets. If you’re using an original object instead of creating an instance of it, calling DestroyImmediate() would actually delete it from your computer. If you’re cloning/making instances of objects, then you don’t have to worry about it. It’s recommended that you use Destroy() instead, since it’s not going to permanently destroy your assets, and you often do not need to deallocate memory immediately in the middle of a frame (Destroy happens to clear them out at the end of a frame, or at least later on in the frame). For more info, check the script reference here.

b. Other than using DestroyImmediate() instead of Destroy(), seems like you’re doing fine.