This problem is weird, maybe I’m just thinking completely wrong.
I will explain the classes:
There is a game class, which holds a abstract base class (Mode) in a field, so all classes which are subclass of that base class can be in that field (all the modes).
Now the following: Sometimes the game class, changes the mode, so the field has to change to an other class. This works and the old class gets eliminated because there are no references left (garbage collector)
BUT: In rarely cases, the mode class itself calls the method in the game class to change it’s mode – but debugger shows me, that the object still must be there because after completing the method, it jumps back to the old mode object and completes the code (which is okay in some point, otherwise it had nowhere to go).
So, how do I eliminate that old mode object to avoid a memory leak? Does the garbage collector do this automatically as soon the script there is complete (just call return in this case?)?
I think you’re misunderstanding garbage collection. Garbage collection happens at some time in the future, not instantly. So your mode class still exists, maybe for longer than you might think, even after the reference in your game class no longer references it.
At some point in the future, the garbage collector will kick in, and see that the “old” mode class no longer has any references and collect it. That may be 300ms later, 5 minutes later, or when the process ends.