I'm trying to make this little game in Java but I seem to have stumbled upon a variable reference problem. My Entity class, which Player extends from, keeps a variable of type Dimension. This Dimension gets set via the constructor of the Entity class like so:
protected Dimension dimension;
public Entity(Dimension dimension) {
this.dimension = dimension;
}
In my player class, this is how I pass the dimension object via his constructur:
public Player(Dimension dimension) {
super(dimension);
}
I also have a Game class, which keeps all the possible dimensions, plus an extra variable called activedimension which keeps a reference to the active game dimension.
private Dimension activedimension;
private Dimension overworld;
private Dimension otherdimension;
public Game() {
overworld = new OverWorldDimension();
otherdimension = new OtherDimension();
activedimension = overworld;
}
When I want my overworld dimension to reset, I use this method:
public void resetOverWorld() {
overworld = new OverWorldDimension();
activedimension = overworld;
}
Now, whenever I call this resetOverWorld method from anywhere, it seems like my activedimension really did refresh, but the dimension stored in my Player/Enitity class didn't. I'm fairly new to Java, so I don't know if I'm doing something wrong with the variable-references being passed through constructors and methods. My application seems to copy a dimension object somewhere instead of passing the reference, but I can't figure out where.
Any help or thoughts are welcome. Thanks in advance ~Krikke
The problem is that you aren't updating the reference in your
Playerclass. When you store yourDimensionin yourEntityconstructor you are storing a reference to thatDimensionin memory. In yourresetOverWorld()method you change theoverworldandactivedimensionvariables to point to a newOverWorldDimensionbut all the references elsewhere (e.g. yourEntityobjects) haven't changed. They still refer to the initialDimensionthey were constructed with.You might want to consider having a
DimensionTrackerclass that yourEntitycould hold instead, allowing you to change it's internalDimensionfrom a single location. Otherwise you need to update everyEntityto refer to the newDimension....
...
...
...