Game Messaging System Design

Posted by you786 on Game Development See other posts from Game Development or by you786
Published on 2012-10-11T05:53:17Z Indexed on 2012/10/11 9:53 UTC
Read the original article Hit count: 229

I'm making a simple game, and have decided to try to implement a messaging system.

The system basically looks like this:

Entity generates message -> message is posted to global message queue -> messageManager notifies every object of the new message through onMessageReceived(Message msg) -> if object wants, it acts on the message.

The way I'm making message objects is like this:

//base message class, never actually instantiated
abstract class Message{
  Entity sender;
}

PlayerDiedMessage extends Message{
  int livesLeft;
}

Now my SoundManagerEntity can do something like this in its onMessageReceived() method

public void messageReceived(Message msg){
  if(msg instanceof PlayerDiedMessage){
     PlayerDiedMessage diedMessage = (PlayerDiedMessage) msg;
     if(diedMessage.livesLeft == 0)
       playSound(SOUND_DEATH);
  }
}

The pros to this approach:

  1. Very simple and easy to implement
  2. The message can contain as much as information as you want, because you can just create a new Message subclass that has whatever info necessary.

The cons:

  1. I can't figure out how I can recycle Message objects to a object pool, unless I have a different pool for each subclass of Message. So I have lots and lots of object creation/memory allocation over time.
  2. Can't send a message to a specific recipient, but I haven't needed that yet in my game so I don't mind it too much.

What am I missing here? There must be a better implementation or some idea that I'm missing.

© Game Development or respective owner

Related posts about architecture

Related posts about messaging