-1

在我最近提出的问题之后(已回答;非常感谢您的帮助!)我进步了一点,但又遇到了另一堵砖墙。我对 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;

        }


    }





}
}
4

1 回答 1

3

您不会将 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;

然后它会被初始化

于 2012-11-15T11:57:10.480 回答