I’m struggling with what I think is basically an architecture problem. I’m good with events and delegates and have used in “regular” programming for years. My current game situation seems to indicate a flaw which maybe I’m over thinking. Anyway here is the scenario.
Turn based strategy game where the player can select the tile objects that make up the map.
I have an InputManager which detects when a user clicks a GameObject. I quiz the target object and if it is a game tile I raise the TileSelected event from the InputManager.
So now I have, say 1000 tiles also with a Tile class that subscribes to the TileSelected event. The idea is that the tile can then do something like change colour or display some kind of visual cue that its been selected. The details of this are irrelevant.
My issue is, that ALL tiles respond to the event as they are all listening. So the first thing I have to do in the event handler is check that the object sent with the event as an argument is equal to the object that the Tile is a component of.
In short, it just feels off that every tile has to go through the process of asking if the event is meant for it.
I hope this make sense. Any input greatly appreciated.
Sorry I meant to add that my initial thought is I have to create a TileManager that holds a reference to the collection of tiles. I get that TileManager to subscribe to the TileSelected event, grab the target from the events payload and then call a method directly on the Tile class. I’m ok with this as a workaround, but still feels a little off. But at least now 1000 objects aren’t going “did you mean me?”
Hi all … still not sure this is the best approach but I’ll document what I ended up with here in case its useful for others.
InputManager still raises the
GameObjectedSelected event passing a target object in its payload (basically the
GameObject that Raycasting hits).
My ‘Tile’ class no longer listens for this event as I have the issue of all tiles responding to the event and as such all of them having to ask “do you mean me”.
I implemented an interface
ISelectable that has a single method (for now)
Select(). I have different classes that implement
ISelectable for each type of object that can be selected (ie
InputManager simply calls
GetComponent<ISelectable>() on the
GameObject hit by Raycasting and if that component is not a null reference I know it is a “selectable” thing and I can call
Select() on that component object.
As I said I still raise the event but it is now only listened to by things like cameras and lights so they can update positions based on the object selected. This is not an issue as there is only one of each of them and in that case responding to the event is always relevant to the listener.
Hope that’s helpful for anyone else struggling with this architecture. Still very interested in hearing any input into this.