XNA未知内存泄漏导致游戏崩溃

时间:2015-12-11 15:08:06

标签: c# debugging memory-leaks xna game-physics

您好!
我正在XNA的太空射击游戏。游戏的工作原理应该是我无法在代码中找到任何错误。然而,当我从太空船上射出太多子弹时,游戏崩溃了。

我确实在屏幕上删除了子弹,但它们仍然导致游戏崩溃。

我得到的错误信息是:

  

"未处理的类型' System.ComponentModel.Win32Exception'发生在System.Drawing.dll"   "其他信息:流程已结束"

标记的行是:

public Bullet(Texture2D texture, Color color, float speed, int scale)  

以下是子弹的相关代码:

Game1.cs

   // This is a member variable at the top of my program
   public List<Bullet> bullets = new List<Bullet>();  

   // Further down
    public void UpdateBullets()
    {
        foreach (Bullet bullet in bullets)
        {
            bullet.position.Y += bullet.speed;
            if (bullet.position.Y >= GraphicsDevice.Viewport.Height || bullet.position.Y + bullet.height <= 0
            || bullet.position.X < 0 || bullet.position.X - bullet.width > GraphicsDevice.Viewport.Width)
                bullet.isVisible = false;
        }
        for (int i = 0; i < bullets.Count(); i++)
        {
            if (!bullets[i].isVisible)
            {
                bullets[i].texture = null;
                bullets[i] = null;
                bullets.Remove(bullets[i]);
            }
        }
    }  

    public void Shoot(Entity e, Texture2D texture)
    {
        Bullet newBullet = new Bullet(texture, e.color, e.bulletSpeed, 16);
        newBullet.owner = e;
        newBullet.SetPositionByBottom(e.bulletPoint);
        newBullet.isVisible = true;

        if (bullets.Count() < maxBullets)
        {
            bullets.Add(newBullet);
        }
    }  

        public void DrawBullets()
    {
        foreach (Bullet bullet in bullets)
        {
            bullet.Draw(spriteBatch);
        }
    }  

Bullet.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace SpaceShooter
{
    class Bullet : GameObject
    {
        public float speed;
        public bool isVisible;
        public Entity owner;

        public Bullet(Texture2D texture, Color color, float speed, int scale)
        {
            this.color = color;
            this.texture = texture;
            this.speed = speed;
            width = scale;
            height = scale * 2;
            isVisible = false;
        }
    }
}  

关于内存泄漏的来源,或者甚至是内存泄漏的任何想法?

1 个答案:

答案 0 :(得分:0)

尝试向后迭代子弹列表:

for (int i = bullets.Count()-1; i >= 0; i--)
{
    if (!bullets[i].isVisible)
    {
        bullets[i].texture = null;
        bullets[i] = null;
        bullets.Remove(bullets[i]);
    }
}

当您在i中删除列表中的项目时,i + 1处的项目会被下推到i,但您现在正在跳过此项目。我认为这可能会导致你的内存泄漏。向后工作应该避免这个问题。