2
\$\begingroup\$

I'm working on a snake game that has multiple game objects (snakes, apples, obstacles), and game modes (classic, adventure), that are DrawableGameComponents. Is it OK that I'm adding them as needed instead of in the main initialization method?

If not, how should I go about drawing and updates components of my game that need to be added in other methods?

If yes, is there any way to get the initialization or load overridden methods to run? Or is making my own load method and calling it right after adding the component how it should be done?

Thanks!

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Yes, you can add (Drawable)GameComponents at any time. When you add them before Game.Initialize (eg: in your game constructor), they will have their Initialize method called when Game.Initialize is called.

If you add them after Initialize is called on your game class, then they will have their Initialize method called when they are added to the Game.Components collection.

Note that the upshot of this is that there is a small window in your game class's Initialize method, in between you calling base.Initialize() and returning, where game components will not be initialized!

Note that Game.Initialize will call LoadContent, so adding components in your LoadContent method also will cause them to not be initialized. Although adding components from a game component Initialize method will work.

DrawableGameComponent.Initialize calls DrawableGameComponent.LoadContent (so don't skip any base calls in methods that you override).


You could also add them at the start of your game and then toggle the Enabled and Visible properties as required.

Alternately, you could skip the game components system all together. It's basically just a list of objects with virtual Update and Draw methods (et cetera). This way you can program things to do exactly what you want.

\$\endgroup\$
2
  • \$\begingroup\$ The initialization method only gets called for certain objects, at certain points, and sometimes doesn't get called at all. More specifically my main menu component doesn't init when being added but my game modes do. If i add a component where i add the main menu the previously working component doesnt init. Do you know why? \$\endgroup\$
    – osum4est
    Commented Oct 5, 2014 at 19:05
  • \$\begingroup\$ There is - what I would describe as - a bug in XNA, where the initialization mode switch-over does not happen until after Initialize returns. See my edit. \$\endgroup\$ Commented Oct 6, 2014 at 3:08

You must log in to answer this question.

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