The below code gives me a ObjectDisposedException. I load the contents in the content loader just fine. It works from time to time but occasionally it throws the exception.
All textures are loaded perfectly and each and every object has the right Texture and actually exists. There is nowhere a line where I unload content.
The error is thrown at the last spriteBatch.End();
What goes wrong?
protected override void Draw(GameTime gameTime)
{
if (startMenu.showMenu)
{
spriteBatch.Begin();
startMenu.Draw(spriteBatch);
spriteBatch.End();
}
if (selectedLevel != null && !startMenu.showMenu)
{
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null,
selectedLevel.GetCamera().getViewMatrix(new Vector2(1.0f)));
for (int layer_inc = 0; layer_inc <= selectedLevel.layers.Count() - 1; layer_inc++)
{
selectedLevel.layers[layer_inc].Draw(gameTime, spriteBatch);
}
if (selectedLevel.GetPlayer().IsAlive())
{
Weapon weapon = selectedLevel.GetPlayer().GetWeapon();
weapon.Draw(gameTime, spriteBatch);
if (selectedLevel.GetPlayer().isMeditating())
{
Player player = selectedLevel.GetPlayer();
MeditationBoost meditationBoost = ((MeditationBoost)player.getBoost());
meditationBoost.Draw(spriteBatch, player.position);
}
if (weapon is ShootableWeapon)
{
ShootableWeapon shootableWeapon = (ShootableWeapon)weapon;
if (shootableWeapon.getAmmo().Count() > 0)
{
for (int ammo_inc = 0; ammo_inc <= shootableWeapon.getAmmo().Count() - 1; ammo_inc++)
{
shootableWeapon.getAmmo()[ammo_inc].Draw(gameTime, spriteBatch);
}
}
}
}
foreach (MovableObject movableObject in selectedLevel.movableObjects)
{
if (movableObject is Enemy)
{
Enemy enemy = (Enemy)movableObject;
ThrowAttack attack = ((ThrowAttack)enemy.getAttack());
if (attack != null && attack.getThrowObject() != null)
{
attack.getThrowObject().Walk(Direction.Right, attack.getThrowObject().speed);
attack.getThrowObject().Update(gameTime);
attack.getThrowObject().Draw(spriteBatch);
}
}
}
updateScreenText(spriteBatch);
try
{
spriteBatch.End();
}
catch (ObjectDisposedException e)
{
Debug.Write(e);
}
}
base.Draw(gameTime);
}
edit:
This is how I load the content dynamically (I give the folder as a string when using this function)
public void Loadlistontent(string contentFolder)
{
DirectoryInfo dir = new DirectoryInfo(Content.RootDirectory + "/" + contentFolder);
if (!dir.Exists)
throw new DirectoryNotFoundException();
FileInfo[] files = dir.GetFiles("*.*");
foreach (FileInfo file in files)
{
if (!textureLoader.GetTextures().ContainsKey(file.Name))
{
string key = Path.GetFileNameWithoutExtension(file.Name);
Texture2D texture = Content.Load<Texture2D>(contentFolder + "/" + key);
textureLoader.addTexture(file.Name, texture);
}
}
}