Effective communication in a component-based system
- by Tesserex
Yes, this is another question about my game engine, which is coming along very nicely, with much thanks to you guys.
So, if you watched the video (or didn't), the objects in the game are composed of various components for things like position, sprites, movement, collision, sounds, health, etc. I have several message types defined for "tell" type communication between entities and components, but this only goes so far. There are plenty of times when I just need to ask for something, for example an entity's position.
There are dozens of lines in my code that look like this:
SomeComponent comp = (SomeComponent)entity.GetComponent(typeof(SomeComponent));
if (comp != null) comp.GetSomething();
I know this is very ugly, and I know that casting smells of improper OO design. But as complex as things are, there doesn't seem to be a better way. I could of course "hard-code" my component types and just have
SomeComponent comp = entity.GetSomeComponent();
but that seems like a cop-out, and a bad one.
I literally JUST REALIZED, while writing this, after having my code this way for months with no solution, that a generic will help me.
SomeComponent comp = entity.GetComponent<SomeComponent>();
Amazing how that works. Anyway, this is still only a semantic improvement. My questions remain.
Is this actually that bad?
What's a better alternative?