开发者

Effective communication in a component-based system

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 an开发者_Python百科d 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?


Why do you assume it's bad?

This is what generics were made for.


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜