Search code examples
javalibgdxscreens

resetting variables in dispose() libgdx


I want the same effect of this.dispose(); without getting StackOverflow errors. How can I dispose of all of my variables ( I have ~100) easily? I want to delete the current screen and switch screens so If I switch back it will be as if the old screen never existed. I have been trying various methods for disposing of the current screen and so far manually disposing in the dispose() method seems to be the best bet.


Solution

  • Manually disposing in the dispose() method of the Screen is the best way in most cases, because for most resources it is the earliest possible and the latest possible point in time to do so. Sometimes if you know that you won't need something anymore before changing the Screen you can also do it already before, but that should be just a special case.

    As for your StackOverflow error: this is not because you have a lot of variables, but because there seems to be any kind of cyclic dependency between your resources that you are disposing. It can be just two resources which both dispose() each other in turns. An example:

    Class A {
        private B b;
    
        public void dispose() {
            b.dispose();
        }
    }
    
    Class B {
        private A a;
    
        public void dispose() {
            a.dispose();
        }
    }
    

    As soon as you call dispose() of one of those two Resources, you will hit an endless loop and eventually a StackOverflow because your function call stack is limited.

    This might also be possible with more than just two Resources, there could be another class C and you might have a circle like A -> B -> C -> A.