In an example game engine server, the game world could be represented by a World object. The game might have multiple game worlds and a player who is in a world only needs to receive position data of units in that world.
class World
{
public List<Unit> Units { get; set; }
}
However a piece of code also needs to be able to look up what world a unit is in easily, so the unit object itself keeps track of a world reference.
class Unit
{
public World World { get; set; }
}
This works for lookup, but quickly becomes problematic when changing data when the programmer isn't aware of the relationship between objects going on, so I changed Units
in World
to be readonly and have the following code in Unit
.
public virtual World World
{
get { return _world; }
set
{
// Unit must always be in a world
Contract.Requires<ArgumentNullException>(value != null);
// If already this, don't do anything
if (value == _world) return;
var oldWorld = _world;
_world = value;
if(oldWorld != null) oldWorld.UpdateUnitEntry(this);
_world.UpdateUnitEntry(this);
}
}
This works, but it feels like there's a better way to do this. Especially as I add more stuff that needs to be linked the same way (a World
also has Structure
s and Player
s), a lot of repeated functionality comes in. Is there a better way to achieve this one-to-many relationship without manually updating both sides?