【问题标题】:.TotalSeconds in C# XNAC# XNA 中的 .TotalSeconds
【发布时间】: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


【解决方案1】:

您不会将 GameTime gameTime 作为参数传递给函数。因此,您无法访问 gameTime,因为它未初始化

public ResourceCounter(Vector2 pos, GameTime gameTime)
{
    // stuff

     currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()

    // other stuff
}

编辑:

如果你将它传递给构造函数,然后创建一个临时变量并使用它

private GameTime gameTime;

然后在构造函数中

this.gameTime = gameTime;

然后会被初始化

【讨论】:

  • 我添加了额外的参数“GameTime gameTime”,但收到“'RealTimeStrategyGame.ResourceCounter' 不包含采用 1 个参数的构造函数”的错误。
  • 在创建 ResourceCounter 时,您需要将主 Game 类中的 gameTime 变量传递给 ResourceCounter 的构造函数。
  • 在调用此函数的代码中,您需要传递一个 GameTime 参数。因此,您将拥有 ResourceCounter(pos, gameTime) 例如。假设您首先在一个带有 gameTime 参数的函数中运行它。
  • 这里的问题并不是真正的 XNA 问题,更多的是您不了解面向对象编程的基础知识。我建议在继续之前搜索传递函数参数,否则你会一次又一次地遇到同样的问题。
  • 在我的主要 Game 类中,(名为 GameScreen.cs)我遇到了新错误:“'RealTimeStrategyGame.ResourceCounter' 不包含带有 1 个参数的构造函数”。这是该类的代码:pSourceCount = new ResourceCounter(new Vector2(30,20)); 编辑:我相信你是正确的。尽管如此,还是感谢大家的帮助,一旦我觉得自己准备好了,我会回到这篇文章。
猜你喜欢
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多