I’m currently programming a library for simple games, mostly intended to be used by myself.
Now I’ve run into a problem. I have a class called “Game” which looks like this:
class Game
{
private List<Entity> entities;
private int counter;
public Game()
{
entities = new List<Entity>();
counter = 0;
}
public AddEntity(Entity entity_)
{
entities.Add(entity_);
// problem! how to inform entity_ that it was added?
counter++;
}
}
Entity is a class which each object that acts in the game must be derived from. Its contents don’t really matter. What I am looking for is a way for Game to inform the newly added entity_ class about its owner (current Game instance) and its id (which is what “counter” is for). Now I have been thinking about using an interface which would have a method “OnAdd(Game owner_, int id_)” for that as that would definitely work, but I wanted to make sure there is no preferred way over that. So that is my question:
Is there a better solution for my problem than interfaces? The Entity instance does not know what Game instance it is being added to, and using methods for event-like purposes doesn’t feel right in my eyes. I could be wrong if course.
If your
Entityhas a property of typeGame, it’s easy to solve this without even using events:and then in the
AddToGamemethod, you would do whatever you would do in your event handler, which now is not necessary.