I am developing an XNA game. This is time I am careful about the architecture. Til today, I have always implemented my own draw method in this way:
public void Draw(SpriteBatch sb, GameTime gameTime)
{
sb.Begin();
// ... to draw ...
sb.End();
}
I was digging the DrawableGameComponent and saw the Draw method comes in this way:
public void Draw(GameTime gameTime)
{
// ...
}
First of all, I know that SpriteBatch can collect many Texture2D between Begin and End, so that it can be useful to sort them, or draw with same Effects.
My question is about the performance and the cost of passing the SpriteBatch. At DrawableGameComponent it is possible to call spritebatch of game object if its spritebatch is public.
What is suggested, what should a xna-game programmer do?
Thanks in advice.
One of the serious disadvantages of
DrawableGameComponentis that you’re locked into its provided method signature. While there’s nothing “wrong”, per se, withDrawableGameComponent, do not think of it as the “one true architecture“. You’re better off thinking of it as an example of a possible architecture.If you find yourself needing to pass a
SpriteBatch(or anything else) to the draw method of a “game component” – the best way is to pass it as an argument. Anything else is convoluted.Obviously this means that you can’t use XNA’s provided
GameComponentsystem, and you have to make your own alternative. But this is almost trivial: At its most basic level, it’s just a list of some base type that has appropriate virtual methods.Of course, if you must use
GameComponent– or your game is so simple (eg: a prototype) that you don’t really care about the architecture – then you can use basically any method you like to get aSpriteBatchto your draw method. They all have disadvantages.Probably the next-most architecturally robust method is to pass your
SpriteBatchinstance into the constructor of each of your components. This keeps your components decoupled from your game class.On the other hand, if you’re throwing architecture to the wind, I’d suggest making your
MyGame.spriteBatchfieldpublic static. This is the simplest way to allow it to be accessed anywhere. It’s easy to implement and easy to clean up later when/if you need to.To answer your question about performance: Anything to do with passing a
SpriteBatcharound will have almost negligible effect on performance (providing the order of calls toDraw/Begin/Endstays the same). Don’t worry about it.(If you see
SpriteBatch whateverin code, that represents a reference. A reference is a 32-bit value (in a 32-bit program, which all XNA games are). That’s the same size as anintor afloat. It’s very small and very cheap to pass around/access/etc.)