Reputation: 2121
So this is my Game1 class :
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace GameName2
{
public class Game1 : Game
{
GraphicsDeviceManager _graphics;
SpriteBatch _spriteBatch;
Texture2D _bg;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
_spriteBatch = new SpriteBatch(GraphicsDevice);
_bg = Content.Load<Texture2D>(@"Loading");
// TODO: use this.Content to load your game content here
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
_spriteBatch.Draw(_bg,
new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
null,
Color.White,
0,
Vector2.Zero,
SpriteEffects.None,
0);
base.Draw(gameTime);
}
}
}
I make a "Content" folder in my project, and add Loading.xnb as existing item. And then, I change the Build Action of the Loading.xnb to "Content" and the Copy to Output as "Copy Always".
But when I compile it, this section throw System.InvalidOperationException
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
_spriteBatch.Draw(_bg,
new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
null,
Color.White,
0,
Vector2.Zero,
SpriteEffects.None,
0);
base.Draw(gameTime);
}
Specifically at the _spriteBatch.Draw(.......) method. Can somebody help me? Thanks.
Upvotes: 1
Views: 523
Reputation: 1936
Look at some of the example programs. _spriteBatch.Draw must be called between _spriteBatch.Begin and _spriteBatch.End.
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
_spriteBatch.Begin();
_spriteBatch.Draw(_bg,
new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
null,
Color.White,
0,
Vector2.Zero,
SpriteEffects.None,
0);
_spriteBatch.End();
base.Draw(gameTime);
Upvotes: 1