6
\$\begingroup\$

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.

\$\endgroup\$
0

2 Answers 2

8
\$\begingroup\$

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.Components.Add(inputComponent);
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: http://www.nuclex.org/articles/architecture/6-game-components-and-game-services

\$\endgroup\$
1
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ +1 for the obvious: if you need a reference then keep one. \$\endgroup\$ Jan 18, 2011 at 7:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .