views:

52

answers:

2

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?
A: 

Without knowing the overall design of your game, it's difficult to know if that pattern, in isolation, is good or bad. If it works and performs well, the only potential argument against it is architectural- will it scale?

Dave Swersky
A: 

I've been working on a game, and I'm using generic type parameters to look up different components in the same way. I got the idea from http://t-machine.org/index.php/2010/05/09/entity-system-1-javaandroid/. I'm not sure it is the best way, it feels like a misuse of the generics system. It works though.

liquorice