ContentManager中的NullReferenceException,XNA
我在XNA中遇到NullReferenceException问题。我有4个职业:英雄,精灵,火球,游戏1。通过调试,我发现问题发生在Fireball通过管道加载内容之后ContentManager中的NullReferenceException,XNA,xna,nullreferenceexception,Xna,Nullreferenceexception,我在XNA中遇到NullReferenceException问题。我有4个职业:英雄,精灵,火球,游戏1。通过调试,我发现问题发生在Fireball通过管道加载内容之后 class Fireball: Sprite { const int MAX_DISTANCE = 500; public bool Visible = false; Vector2 mStartPosition; Vector2 mSpeed;
class Fireball: Sprite
{
const int MAX_DISTANCE = 500;
public bool Visible = false;
Vector2 mStartPosition;
Vector2 mSpeed;
Vector2 mDirection;
public void LoadContent(ContentManager theContentManager)
{
base.LoadContent(theContentManager, "Fireball");
Scale = 0.3f;
}
然后在我的Sprite类中,我试图通过ContentManager加载我的纹理
class Sprite
{
//The asset name for the Sprite's Texture
public string AssetName;
//The Size of the Sprite (with scale applied)
public Rectangle Size;
//The amount to increase/decrease the size of the original sprite.
private float mScale = 1.0f;
//The current position of the Sprite
public Vector2 Position = new Vector2(0, 0);
//The texture object used when drawing the sprite
private Texture2D myTexture;
//Load the texture for the sprite using the Content Pipeline
public void LoadContent(ContentManager theContentManager, string theAssetName)
{
myTexture = theContentManager.Load<Texture2D>(theAssetName);
AssetName = theAssetName;
Source = new Rectangle(0, 0, myTexture.Width, myTexture.Height);
Size = new Rectangle(0, 0, (int)(myTexture.Width * Scale), (int)(myTexture.Height * Scale)); ;
}
类精灵
{
//精灵纹理的资源名称
公共字符串资产名;
//精灵的大小(应用了比例)
公共矩形尺寸;
//增加/减小原始精灵大小的量。
私人浮动mScale=1.0f;
//精灵的当前位置
公共向量2位置=新向量2(0,0);
//绘制精灵时使用的纹理对象
私有纹理2D myTexture;
//使用内容管道加载精灵的纹理
public void LoadContent(ContentManager-theContentManager,string-theAssetName)
{
myTexture=ContentManager.Load(AssetName);
资产名称=资产名称;
Source=新矩形(0,0,myTexture.Width,myTexture.Height);
大小=新矩形(0,0,(int)(myTexture.Width*Scale),(int)(myTexture.Height*Scale));
}
在myTexture=ContentManager.Load(AssetName);行中,它给了我一个NullReferenceException。通过调试报告,我看到资产名有“Fireball”在它里面,但是ContentManager本身是空的。我做错了什么?因为我是C#新手,如果有人能告诉我应该添加哪些行以及在哪里,我将不胜感激。如果有人需要一个完整的项目,它就在这里,因为它有点大。你不是在Game1中为fireball调用LoadContent,这意味着你没有ContentManager。 将此添加到您的精灵类:
public static ContentManager Cm;
然后在Game1中的LoadContent顶部
Sprite.Cm = this.Content;
然后它应该可以正常工作,因为您保存了ContentManager以供以后在Sprite类中使用。我运行了整个项目,但工作正常,我忘记添加了!只有在您单击右键Ctrl时才会加载Fireball纹理。试试看。没问题,随时乐意帮助:)