gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:29:31 26 4
gpt4 key购买 nike

您好!
我正在 XNA 开发一款太空射击游戏。游戏运行正常,我在代码中找不到任何错误。但是,当我从我的宇宙飞船发射太多子弹时,游戏就会崩溃。

当子弹离开屏幕时,我确实删除了它们,但它们仍然导致游戏崩溃。

我得到的错误信息是:

"An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.Drawing.dll" "Additional information: The process has ended"

标记的行是:

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);
}
}

子弹.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;
}
}
}

关于内存泄漏的来源有任何想法,或者它是否根本就是内存泄漏?

最佳答案

尝试向后迭代项目符号列表:

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,但您现在将跳过该项目。我认为这可能会导致您的内存泄漏。逆向工作应该可以避免这个问题。

关于c# - XNA未知内存泄漏导致游戏崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com