XNA game components

我的未来我决定 提交于 2019-12-06 06:50:42

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>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!