Effective communication in a component-based system

Posted by Tesserex on Stack Overflow See other posts from Stack Overflow or by Tesserex
Published on 2010-05-12T14:50:47Z Indexed on 2010/05/12 15:04 UTC
Read the original article Hit count: 201

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.

  1. Is this actually that bad?
  2. What's a better alternative?

© Stack Overflow or respective owner

Related posts about c#

Related posts about components