- Home /
Memory Leak: Base Class Script duplication on load
The characters in our game are derived from a base class script, which is not attached to any object.
When a level is reloaded or a new level is loaded the character is destroyed, but the base class script remains and when the new character is created at the start of the next level an additional base class script is created.
I know this is happening because the score is incremented in the base class. When the score is increased by 100 in the first level, the score goes up by 100, if the same level is reloaded or the next level is loaded the same 100 point increase results in a 200 point increase. Each reload adds 100 to the score every time it is updated. The object that sends the score update only sends the message once, but there are multiple objects adding 100 to the score (one for each retry or reload)... I'm assuming this is because the Base Class script is being duplicated.
So my question is how can I clean these duplicate scripts from the scene?
I've tried Resources.UnloadUnusedAssets(), with no result, also GC.Collect()
I'm stumped...
It sounds a lot like what DontDestroyOnLoad() would do: add a script instance on every scene load. In any case it is not related to Resources, GC and I'm confident 'leaking base class' is actually impossible. Are you sure the character GameObject aren't piling up, too?
Answer by kalvinlyle · Mar 10, 2012 at 06:52 PM
I solved this by loading a empty scene between levels.
Answer by Kryptos · Jan 11, 2012 at 09:59 PM
You wrote:
but the base class script remains and when the new character is created at the start of the next level an additional base class script is created.
That does not make any sense. Your misunderstood the concept of base class and inheritance. When you use an instance of a script that inherits another script (base class) there is only one script instantiated.
IMHO the whole object is leaking between scene. This can happen if you have another script that is not destroyed between scene and that keeps a reference to your so-called 'leaking' script.
Make sure to release any references (and cross-references) before loading another scene.
OnDestroy() method which is called on every active component upon their destruction call be of some use in this case.
Also, make sure that the score variable is not static, as that would cause the value to persist between levels (I think).
Yeah, I think it would, actually! I've never tested this, because I avoid static variables when I can, but this is actually another reason not to use them...
I believe the problem is duplicating script instance and not persistent data but yeah - testing shows a static variable is apparently persistent through scene loads and object destructions.
Your answer
![](https://koobas.hobune.stream/wayback/20220613062846im_/https://answers.unity.com/themes/thub/images/avi.jpg)