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
Player
class. When you store yourDimension
in yourEntity
constructor you are storing a reference to thatDimension
in memory. In yourresetOverWorld()
method you change theoverworld
andactivedimension
variables to point to a newOverWorldDimension
but all the references elsewhere (e.g. yourEntity
objects) haven't changed. They still refer to the initialDimension
they were constructed with.You might want to consider having a
DimensionTracker
class that yourEntity
could hold instead, allowing you to change it's internalDimension
from a single location. Otherwise you need to update everyEntity
to refer to the newDimension
....
...
...
...