A second useful decoupling pattern in MonoGame is the use of game components. You’ve probably noticed that many of the classes you have written have a similar pattern: they each have a LoadContent()
, Update()
, and Draw()
method, and these often take the same arguments. In your game class, you probably mostly invoke these methods for each class in turn. MonoGame provides the concept of game components to help manage this task. This involves: 1) a GameComponentCollection
which game components are registered with, and components are implemented by extending the GameComponent
or DrawableGameComponent
base classes.
The Game
implements a GameCollection
in its Components
property. It will iterate through all components it holds, invoking the Update()
and Draw()
methods within the game loop.
GameComponent
The GameComponent
base class implements IGameComponent
, IUpdatable
, and IDisposable
interfaces. It has the following properties:
Enabled
- this boolean indicates if the component will be updatedGame
- the game this component belongs toUpdateOrder
- an integer used to sort the order in which game component’sUpdate()
method is invoked
It also has the following virtual methods, which can be overridden:
Dispose(bool disposing)
- Disposes of the componentInitialize()
- Initializes the component; used to set/load any non-graphical content; invoked during the game’s initialization stepUpdate(GameTime gameTime)
- Invoked every pass through the game loop
Finally, it also implements the following events:
EnabledChanged
- triggered when theEnabled
property changesUpdateOrderChanged
- triggered when theUpdateOrder
property changes
DrawableGameComponent
The DrawableGameComponent
inherits from the GameComponent
base class, and additionally implements the IDrawable
interface. In addition to its inherited properties, it declares:
DrawOrder
- an integer that determines the order game components are drawn inGraphicsDevice
- the graphics device used to draw the game componentVisible
- a boolean that determines if the game component should be drawn
It also has the additional virtual methods:
LoadContent()
- Loads graphical content, invoked by the game during its content loading stepDraw(GameTime gameTime)
- Draws the game component, invoked during the game loop
Finally, it implements the additional properties:
DrawOrderChanged
- triggered when theDrawOrder
property changesVisibleChanged
- triggered when theVisible
property changes
The concept of Game Component espoused by MonoGame is not the same one defined by the Component Pattern, though it could potentially be leveraged to implement that pattern.