Say you’re developing an RTS or maybe a connect-the-dots sort of game. What would be the easiest way to go about handling object selection? This is my suggested solution.
In the given example, I’m taking advantage of the object-mouse event handling that MonoBehaviours on GameObject with colliders on them give for free. You might be in a scenario where raycasting or otherwise resolving selection requests makes more sense, but the basic logic still applies. This example is merely intended to get your from start to goal as fast as possible.
First off, we need a selection manager class (cleverly named SelectionManager in my example). This is where we store selection state and via static accessors, we can get and modify the current selection. Seeing as this class is both public and all accessors are static, you can put its source anywhere. In my example I’ve simply put it right after the MonoBehaviour used for testing it.
And the promised MonoBehaviour using the SelectionManager class:
And that is all there is to it. By popular demand, I’m now starting to provide pre-built projects with these tips and tricks posts. Download, unzip, open and play. Requires Unity 2.6.1: