Search code examples
xnaxna-4.0xnanimation

XNA game components


I an confused about how to pass values of variables from 1 gamecomponent to another. I am using xna 4.0.

I created two gamecomponents, the drawstring and the inputmanager. I want to read the keyboard input of the user and pass it onto drawstring where it will update the position.

I cant add components on drawstring(drawablegamecomponent). I can do it on class but not on gamecomponent. Can you guys post some examples here. For beginners.


Solution

  • Use GameComponent for something that you would want to have Update called on every frame, and use DrawableGameComponent for something that you would want to have Draw called on every frame and LoadContent called when appropriate (at the start of the program, as well as whenever the device is lost, like when the user pressed Ctrl-Alt-Del on Windows).

    For InputManager you might want an Update method, so that you can keep user input updated, so InputManager could be a GameComponent. DrawString doesn't sound like it needs to be. Both classes sound like they could be services. In the constructor or Initialize method of your game class, do something like the following:

    Components.Add(mInputManager = new InputManager(this));
    Services.AddService(typeof(InputManager), mInputManager);
    Services.AddService(typeof(DrawString), mDrawString = new DrawString(this))
    

    (DrawString and any other class that you want to get game services from will need a reference to the Game object.)

    (Note that GameComponents do not necessarily need to be services, and services do not need necessarily need to be GameComponents. To get Update and/or Draw to be called, you must call Components.Add(...); separately, to get an object to be retrievable as a service, you must call Services.AddService(...)).

    Then, when you would like to use the InputManager or DrawString service in some other game component (or any class that you have passed a reference to your game object), you can do this:

    InputManager input = (InputManager)Game.Services.GetService(typeof(InputManager));
    

    Personally, I write an extension method to make that more concise:

    using XNAGame = Microsoft.XNA.Framework.Game;
    
    ...
    
       public static T GetService<T>(this XNAGame pXNAGame)
       {
          return (T)pXNAGame.Services.GetService(typeof(T));
       }
    

    The line to get the input service then becomes:

    InputManager input = Game.GetService<InputManager>();