Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am creating a simple input component to hold on to actions and key states, and a short history of the last ten or so states. The idea is that everything that is interested in input will ask this component for the latest input, and I am wondering where I should create it.

I am also wondering how I should create components that are specific to my game objects - I envision them as variables, but then how do their Update/Draw methods get called?

What I'm trying to ask is, what are the best practices for adding components to the proper collections? Right now I've added my input component in the main Game class that XNA creates when everything is first initialized, saying something along the lines of this.Components.Add(new InputComponent(this)), which looks a little odd to me, and I'd still want to hang onto that reference so I can ask it things.

An answer to my input component's dilemma is great, but also I'm guessing there is a right way to do this in general in XNA.

share|improve this question
up vote 8 down vote accepted

You're on the right track. Getting a reference to a GameComponent from other GameComponents relies on GameServices.

Revised code would look something like:

var inputComponent = new InputComponent(this);
this.Services.Add(typeof(IInputComponent), inputComponent);

Getting the component back out from another component would look like:

var inputService = (IInputComponent)Game.GameServices.GetService(typeof(IInputComponent));

More information about the GameComponent and GameServices architecture can be found here:

share|improve this answer

From examples I've seen, the best way to instantiate a component and then use it depends on what type of component it is. For the mentioned input component, keep a reference to it in the main Game class in XNA, and in the Game's Update() method, add a line like input.Update(referenceToSomethingIfNeeded) so that the Game class manages its component updates. For other components that are needed within specific game objects, have the game object Update() methods do the same for their components.

share|improve this answer
+1 for the obvious: if you need a reference then keep one. – michael.bartnett Jan 18 '11 at 7:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.