Initializing entities vs having a constructor parameter
Posted
by
Vee
on Game Development
See other posts from Game Development
or by Vee
Published on 2012-05-14T10:09:06Z
Indexed on
2012/09/11
21:50 UTC
Read the original article
Hit count: 293
c#
|entity-system
I'm working on a turn-based tile-based puzzle game, and to create new entities, I use this code:
Field.CreateEntity(10, 5, Factory.Player());
This creates a new Player at [10; 5]. I'm using a factory-like class to create entities via composition.
This is what the CreateEntity method looks like:
public void CreateEntity(int mX, int mY, Entity mEntity)
{
mEntity.Field = this;
TileManager.AddEntity(mEntity, true);
GetTile(mX, mY).AddEntity(mEntity);
mEntity.Initialize();
InvokeOnEntityCreated(mEntity);
}
Since many of the components (and also logic) of the entities require to know what the tile they're in is, or what the field they belong to is, I need to have mEntity.Initialize(); to know when the entity knows its own field and tile.
The Initialize(); method contains a call to an event handler, so that I can do stuff like this in the factory class:
result.OnInitialize += () => result.AddTags(TDLibConstants.GroundWalkableTag, TDLibConstants.TrapdoorTag);
result.OnInitialize += () => result.AddComponents(new RenderComponent(), new ElementComponent(), new DirectionComponent());
This works so far, but it is not elegant and it's very open to bugs. I'm also using the same idea with components: they have a parameterless constructor, and when you call the AddComponent(mComponent); method in an entity, it is the entity's job to set the component's entity to itself.
The alternative would be having a Field, int, int parameters in the factory class, to do stuff like:
new Entity(Field, 10, 5);
But I also don't like the fact that I have to create new entities like this. I would prefer creating entities via the Field object itself.
How can I make entity/component creation more elegant and less prone to bugs?
© Game Development or respective owner