This site requires JavaScript, please enable it in your browser!
Greenfoot back
Gerrit486
Gerrit486 wrote ...

2022/8/18

How to keep a variable even after restarting Greenfoot?

Gerrit486 Gerrit486

2022/8/18

#
So what I want to do is keep a variable like for example which level has been unlocked and not reset it whenever the program is restarted. I first thought about making Greenfoot write the variables in a text file but I had no luck with that. Are there any ways I can keep variables after restarting the game? Take for example 3 levels boolean levelOneUnlocked = true; boolean levelTwoUnlocked = false; boolean levelThreeUnlocked = false; Now if the player beats level one, I want to unlock level two. However if I were to restart Greenfoot, the variable would be reset back to false. Is there any way I can prevent that?
rdFx rdFx

2022/8/18

#
You could use static fields to keep track of which levels were unlocked before: // the values set here are only set once and not overwritten when instantiating a new (world) class object static boolean levelOneUnlocked = false; static boolean levelTwoUnlocked = false; static boolean levelThreeUnlocked = false; Keep in mind that you need to access static variables via class, not via instance. I presume that your variables are declared in class MyWorld: MyWorld.levelOneUnlocked
danpost danpost

2022/8/18

#
rdFx wrote...
You could use static fields to keep track of which levels were unlocked before:
This will work during a single session, but will not work when going from one session to the next (scenario is closed and reopened -- or recompiled). For that, you will have to use a file or database to store the progress. A file is sufficient provided you do not upload the scenario onto a website. To work on a webpage, Greenfoot provides the UserInfo class to allow variables to have their changing values stored in a database.
You need to login to post a reply.