Etarnalazure
Etarnalazure

Reputation: 198

XNA c# Out of Memory problem

Right, ill start from the beginning so it will be alittle easier to read through,

When ever i run my program it shows everything as it should. i can even walk around with my player for a bit, but suddenly after 10-15 seconds it just dies saying that its out of memory. i have no idea what this means as i have never had this problem before with ealier programs i have made.

here is the code the problem comes from (well that is the code i get shown)

private void Render()
     {

         dc.DrawImage(Image.FromFile("Graphics/WorldAreas/Starting-room.png"), 0, 0);


         foreach (GameObject go in gameWorld)
         {
             go.Render(dc);
         }

         bg.Render();
     }

After the few seconds it highlights "dc.DrawImage" and says that OutOfMemoryException was unhandled.

before i rewrote this i saw that someone asked for the gameobject so ill add the code for that as well

public abstract class GameObject
{


    protected PointF position; //X,Y Position in the Game World
    public PointF Position
    {
        get { return position; }

    }
    protected Image sprite;

    public virtual void Move(float factor)
    {

    }
   public virtual void Render(Graphics dc)
   {
       dc.DrawImage(sprite, position.X, position.Y, sprite.Width, sprite.Height);
       //dc.DrawRectangle(new Pen(Color.Red), CollisionRectangle);
   }


}

hopefully this was a better explaination. and hopefully someone can see the error that i cannot.

thanks in advance :)

Upvotes: 1

Views: 725

Answers (1)

Ian
Ian

Reputation: 34489

I think you're problem is that you are loading a PNG everytime render is called. Instead load this once, and make it a static member on the class for example.

Then, use that single reference for drawing. The reason for this is that Image implements IDisposable so it doesn't release it's resources (memory) after it goes out of scope. If you were to leave it in the Render you'd want to call Image.Dispose() or use a using(Image img = Image.FromFile(..)). But I'd still go for the load it once to reduce I/O.

 private static Image StartRoomImage = Image.FromFile("Graphics/WorldAreas/Starting-room.png");
 private void Render()
 {

     dc.DrawImage(StartRoomImage , 0, 0);

     foreach (GameObject go in gameWorld)
     {
         go.Render(dc);
     }

     bg.Render();
 }

Upvotes: 2

Related Questions