Drawable Game Component Item Template

From XNAWiki
Jump to: navigation, search

You may have noticed the lack of a 'Drawable Game Component' item in the XNA project items list. There's a 'Game Component' item and while its not too much work to make it inherit from DrawableGameComponent instead of GameComponent, it does get rather tedious to do when you're writing a lot of game components. I'm not sure why it wasn't included in the first place, but I've created my own 'Drawable Game Component' item that I can use. Its rather easy to do.

First, create add a new item to your XNA project - selecting 'Game Component' from the item list. Change the class inheritance from GameComponent to DrawableGameComponent.

public class DrawableGameComponentTemplate : Microsoft.Xna.Framework.DrawableGameComponent

Override the LoadContent and Draw methods.

/// <summary>
        /// Loads any component specific content
        /// </summary>
        protected override void LoadContent()
        {
            // TODO: Load any content
 
            base.LoadContent();
        }
 
        /// <summary>
        /// Allows the game component to draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Draw(GameTime gameTime)
        {
            // TODO: Add your drawing code here
 
            base.Draw(gameTime);
        }
  • Select File > Export Template...
  • Select 'Item Template' as the template type.
  • Select your newly created source file on the 'Select Item to Export' page.
  • Select the Microsoft.Xna.* libraries on the 'Select Item References' page.
  • On the 'Select Template Options' page, give your template a meaningful name (like Drawable Game Component) and description.

Once you've created your template, it should show up in the 'Add New Item' dialog items list. Even though the template options has an option to load the template into Visual C#, I had to close and restart Visual C# before the template was available. The item template appears in the 'My Templates' section below all of the regular item templates.

Creating templates can be a huge time saver when you repeatedly create similar classes. Check the MSDN documentation on project and item templates too - you can modify your templates after you've created them and use special keywords/tokens to automatically replace text.