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

2018/3/4

Re-using / Saving variables after resetting the game

Moritz1508 Moritz1508

2018/3/4

#
Hello, I'm wondering if it is possible to keep the value of specific variables after a reset. I need this for a highscore-display which i made for a little snake game. Sadly i couldn't find anything helpful on this question in other user topics. It would be very nice if anybody could help me with that! Greetings, Moritz1508
danpost danpost

2018/3/4

#
Moritz1508 wrote...
I'm wondering if it is possible to keep the value of specific variables after a reset.
Use a class variable instead of an instance variable. Just add the 'static' modifier to the declaration line of the field. For example:
public int highScore; // belongs to an object created from the class or from any of its subclasses

public static int highScore; // belongs to the class itself
The first line shows an instance field. Any object that is considered to be of the type represented by the class will get its own field with the name given. These fields are created at the time the objects are created. Line 3 shows a class field. It is created when the project is compiled (or when the Class object is created -- an object of type Class). These fields do not re-initialize when you reset your project -- only when you re-compile it.
You need to login to post a reply.