我有兩個類:Game1和Animation。 我總是得到「沒有設置對象實例的對象引用」。錯誤消息在Game1類的這一行中:animation.Draw(spriteBatch); 有什麼不對?我不知道要改變什麼。未將對象引用設置爲對象的實例。哪裏不對?
Animation class code:
public class Animation
{
private int _animIndex;
public TimeSpan PassedTime { get; private set; }
public Rectangle[] SourceRects { get; private set; }
public Texture2D Texture {get; private set; }
public TimeSpan Duration { get; private set; }
public Animation(Rectangle[] sourceRects, Texture2D texture, TimeSpan duration)
{
for (int i = 0; i < sourceRects.Length; i++)
{
sourceRects[i] = new Rectangle((sourceRects.Length - 1 - i) * (Texture.Width/sourceRects.Length), 0, Texture.Width/sourceRects.Length, Texture.Height);
}
SourceRects = sourceRects;
Texture = texture;
Duration = duration;
}
public void Update(GameTime dt)
{
PassedTime += dt.ElapsedGameTime;
if (PassedTime > Duration)
{
PassedTime -= Duration; // zurücksetzen
}
var percent = PassedTime.TotalSeconds/Duration.TotalSeconds;
_animIndex = (int)Math.Round(percent * (SourceRects.Length - 1));
}
public void Draw(SpriteBatch batch)
{
batch.Draw(Texture, new Rectangle(0, 0, Texture.Width/SourceRects.Length, Texture.Height), SourceRects[_animIndex], Color.White);
}
}
Game1 class code:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Animation animation;
Texture2D gegner;
Rectangle[] gegnerbilder = new Rectangle[10];
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
gegner = Content.Load<Texture2D>("kurzeanim");
}
protected override void Update(GameTime gameTime)
{
KeyboardState kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.A))
{
animation = new Animation(gegnerbilder, gegner, TimeSpan.FromSeconds(3));
animation.Update(gameTime);
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
animation.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
「動畫」只在'Update'中初始化,而不在'Draw'中初始化。這就是爲什麼你在'Draw'中得到異常。使用構造函數初始化字段。 –
我看不出這個問題將來會如何幫助其他讀者。很高興你發現了你的bug。 – Jodrell
您正在有條件地分配動畫實例。你能確保你的動畫對象不爲null。 –