2015-06-23 2 views
0

Я уже некоторое время сталкивался с тем же вопросом, когда игрок собрал объект из игры, он удаляется, но игра все еще думает, что она есть и броски:C# XNA - Утилизируйте графику после того, как они были собраны.

необработанное исключение типа «System.ComponentModel.Win32Exception» произошло в System.Drawing.dll

Дополнительная информация: операция успешно завершена

Я прочитал несколько других сообщений и они, кажется, говорят, что вы должны использовать Dispose(), чтобы удалить графику после того, как они были собраны, чтобы освободить память, но я не уверен, что это правильное решение для меня и я не знаю, как это сделать. .

Предупреждение выше происходит в моем классе Object (он специально подчеркивает линию public Obj(Vector2 pos), это можно увидеть ниже

class Obj : Microsoft.Xna.Framework.Game 
{ 
    public Vector2 position; 
    public float rotation = 0.0f; 
    public Texture2D spriteIndex; 
    public string spriteName; 
    public float speed = 0.0f; 
    public float scale = 1.0f; 
    public bool alive = true; 
    public Rectangle area; 
    public bool solid = false; 

    public int score; 


    public Obj(Vector2 pos) 
    { 
     position = pos; 
    } 

    private Obj() 
    { 

    } 


    public virtual void Update() 
    { 
     if (!alive) return; 

     UpdateArea(); 
     pushTo(speed, rotation); 
    } 



    public virtual void LoadContent(ContentManager content) 
    { 
     spriteIndex = content.Load<Texture2D>("sprites\\" + spriteName); 
     area = new Rectangle((int)position.X - (spriteIndex.Width/2), (int)position.Y - (spriteIndex.Height/2), spriteIndex.Width, spriteIndex.Height); 
    } 


    public virtual void Draw(SpriteBatch spriteBatch) 
    { 
     if (!alive) return; 

     Rectangle Size; 
     Vector2 center = new Vector2(spriteIndex.Width/2, spriteIndex.Height/2); 

     spriteBatch.Draw(spriteIndex, position, null, Color.White, MathHelper.ToRadians(rotation), center, scale, SpriteEffects.None, 0); 
    } 

    public bool Collision(Vector2 pos, Obj obj) 
    { 
     Rectangle newArea = new Rectangle(area.X, area.Y, area.Width, area.Height); 
     newArea.X += (int)pos.X; 
     newArea.Y += (int)pos.Y; 

     foreach (Obj o in Items.objList) 
     { 
      if (o.GetType() == obj.GetType() && o.solid) 
       if (o.area.Intersects(newArea)) 
        return true; 
     } 
     return false; 
    } 

    public Obj Collision(Obj obj) 
    { 
     foreach (Obj o in Items.objList) 
     { 
      if (o.GetType() == obj.GetType()) 
       if (o.area.Intersects(area)) 
        return o; 
     } 
     return new Obj(); 
    } 

    public void UpdateArea() 
    { 
     area.X = (int)position.X - (spriteIndex.Width/2); 
     area.Y = (int)position.Y - (spriteIndex.Height/2); 
    } 

    public T CheckCollisionAgainst<T>() where T : Obj 
    { 
     // If collision detected, returns the colliding object; otherwise null. 
     return Items.objList 
      .OfType<T>() 
      .FirstOrDefault(o => o.area.Intersects(area)); 
    } 

    public virtual void pushTo(float pix, float dir) 
    { 
     float newX = (float)Math.Cos(MathHelper.ToRadians(dir)); 
     float newY = (float)Math.Sin(MathHelper.ToRadians(dir)); 
     position.X += pix * (float)newX; 
     position.Y += pix * (float)newY; 
    } 
} 
+0

Это может быть полезно HTTP : //stackoverflow.com/questions/12954227/in-xna-what-is-the-best-method-to-dispose-of-textures-i-no-longer-need – Dave

+0

@Dave Это помогает, но я не знаете, как я должен применить это к моей игре, чтобы удалить предупреждение –

+0

вы звоните 'spritebatch.begin()' и 'spritebatch.end()'? –

ответ

0

попробовать что-то вдоль линий:

protected override void Dispose(bool disposing) 
{ 
    spriteIndex.Dispose() 
    // any other object to dispose 
    base.Dispose(disposing); 
} 
+0

Где именно следует добавить это? –

+0

в вашем class Obj – Nostradamus

+0

Я сделал так, но дана ошибка: «Microsoft.Xna.Framework.Vector2 не содержит определения для Dispose и никакого метода расширения Утилизируйте прием первого аргумента типа –

Смежные вопросы