Unity – Keeping objects modular with SendMessage()

I’m a fan of being modular with my code, so I’ve been breaking up every game object in Roadtrip into a collection of components: the player object has a component to gather input, another to apply walking movement, another to handle flashlight position and state, and so on. Unity seems to be built around the idea of the GameObject as a collection of components, so this works very well for the most part.

The problem with this setup is that you often run into the need for components to communicate – the flashlight component needs to know that the player pressed the key that turns the flashlight on, for example.  So you start creating references to the other components, and pretty soon everything is dependent on everything else and you might as well have written it all as one script in the first place.

Player GameObject open in the inspector

Roadtrip’s player GameObject open in the inspector

Thankfully, Unity has a GameObject method called SendMessage() that helps to solve this issue, and I’ve been using it all over the place in Roadtrip. SendMessage() lets you call a method on all components attached to an object, and it ignores components that don’t have a definition of that method, without causing an error. For example, when the player enters a vehicle, a message is sent out to all components in the player GameObject called “OnEnterVehicle”. The component that handles movement on foot responds by shutting itself off, and the component responsible for flashlight control automatically turns off the light.

After building this system into the core design of the player GameObject, it becomes very easy and straightforward to add new functionality to the player without having to go around changing a bunch of different scripts. It also means far fewer dependencies, which keeps the part of me that insists on modular design very happy. Want to add a radio to the truck that turns on automatically when a player gets in? It’s a simple matter of creating a new component for the radio and having it respond to the OnPlayerEnter message. There’s no need to have the main Truck script hold a reference to the radio. In fact, the radio doesn’t even need a reference to the truck, meaning we could potentially reuse the same script for a standalone radio in the world! How’s that for modular design!

Advertisements

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: