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

2016/2/5

Saving a Save Variable Between Worlds But Reset It When Using Reset Button

Geotan Geotan

2016/2/5

#
I am making a game based on the Legend of Zelda NES. I am trying to make it so the main character can pick up a sword, and the sword will stay with him between all the worlds/areas. The only way I could figure out how to do this was using a static variable, but it doesn't reset when I reset Greenfoot, which I need so he has to pick up the sword again. I don't really have any code trying to do this because I couldn't find anything online, so any help appreciated.
danpost danpost

2016/2/5

#
In a game like that, it is best to maintain the same main character and not create a new main character when changing worlds/areas. This main character should only be created once -- in your initial World subclass constructor. If you need to create another instance of a world that is the same type as your initial World object, then you will need two constructors for that world. The second one is the one called programmatically to create all subsequent instances of that world -- one that does NOT create a new main character. Maybe just passing the main character in the parameter of the world constructor would be enough for that. However, you did not give enough information for me to know whether you are maintaining your different worlds/areas or creating new instances of them throughout the game. Anyway, the basic changes if creating multiple instances of your worlds/areas throughout would be:
1
2
3
4
5
6
7
8
9
10
// change this initial world constructor declaration line (name assumed)
public AreaOne()
// to this (main character name assumed) for creating subsequent instances of this class
public AreaOne(MainCharacter mainCharacter)
 
// add new constructor for creating initial AreaOne object
public AreaOne()
{
    this(new MainCharacter());
}
Your other world/area constructors should also be made to receive the main character and should not create a new instance of it. As long as the reference to the sword is kept by the main character, it will be passed along with the main character from world/area to world/area.
You need to login to post a reply.