【发布时间】:2012-11-15 11:47:53
【问题描述】:
在我最近提出的问题之后(已回答;非常感谢您的帮助!)我进步了一点,但又遇到了另一堵砖墙。我对 C# 还很陌生,似乎无法解决我收到的错误消息:“'NullReferenceException 未处理'对象引用未设置为对象的实例”。我正在尝试创建某种计时器,每 2 秒从 1 缓慢计数到 50。我正在使用的代码如下。如果我提供的内容不充分,请告诉我,我会修改。
namespace RealTimeStrategyGame
{
class ResourceCounter
{
Vector2 position;
Texture2D sprite;
Rectangle boundingbox;
bool over, clicked;
SpriteFont font;
GameTime gameTime;
int pSourceCount = 1;
int limit = 50;
float countDuration = 2f; //every 2s.
float currentTime = 0f;
public ResourceCounter(Vector2 pos, GameTime gameTime)
{
position = pos;
over = false;
clicked = false;
gameTime = new GameTime();
currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
if (currentTime >= countDuration)
{
pSourceCount++;
//any actions to perform
}
if (pSourceCount >= limit)
{
pSourceCount = 0;//Reset the counter;
}
}
}
}
【问题讨论】:
-
哪一行给出了你的空引用异常?
-
currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;我知道这一定是一个简单的答案,但我就是想不通!编辑:啊,难道我没有介绍任何地方来读出 TotalSeconds 吗?我在 Main 类中使用了诸如 position 之类的变量(我希望它在屏幕上读出)但没有给它任何显示的东西?
-
你的
gameTime变量必须为空,你能告诉我们声明它的代码吗? -
@Sean 在问题中显示的代码上方,我有: namespace RealTimeStrategyGame { class ResourceCounter { Vector2 position; Texture2D 精灵;矩形边界框; bool over,点击; SpriteFont 字体;游戏时间游戏时间;
-
如果您有更多/更新的代码要发布,编辑您的问题,以便我们可以在上下文中看到它的正确格式。
标签: c# visual-studio-2010 xna