“textureName”在当前上下文中不存在

时间:2013-11-25 02:04:21

标签: c# xna draw texture2d

我遇到了一个问题,我似乎无法在loadContent方法之外的任何地方识别任何纹理。

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    Texture2D tileStart = Content.Load<Texture2D>("tile_start");
    Texture2D tileCrossJunction = Content.Load<Texture2D>("tile_crossjunction");
    Texture2D tileTJunction = Content.Load<Texture2D>("tile_t-junction");
    Texture2D tileCorner = Content.Load<Texture2D>("tile_corner");
    Texture2D tileHallway = Content.Load<Texture2D>("tile_hallway");
    Texture2D tileDeadEnd = Content.Load<Texture2D>("tile_deadend");
    Texture2D sqrPlayer = Content.Load<Texture2D>("sqr_player");
    Texture2D sqrBaddieSmall = Content.Load<Texture2D>("sqr_baddie_small");
    Texture2D sqrBaddie = Content.Load<Texture2D>("sqr_baddie");
    Texture2D sqrBaddieLarge = Content.Load<Texture2D>("sqr_baddie_large");
}

此方法没有问题,但是当我尝试在Draw方法中引用任何这些纹理时......

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.DarkGray);
    base.Draw(gameTime);
    spriteBatch.Begin();
    spriteBatch.Draw(tileStart, new Vector2(0,0), Color.White);
    spriteBatch.End();
}

我收到错误“tileStart在当前上下文中不存在。”

通常情况下,我会说它没有被识别,因为tileStart是在LoadContent方法中声明的变量,因此无法在其他任何地方使用。我感到困惑的原因是我读过的每个教程都显示了这种确切的语法,在这些情况下似乎工作得很好,所以很明显这里还有其他一些我不理解的东西。

非常感谢你们提供的任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

在C#中,变量的“范围”定义明确。在您的代码中,纹理是在方法“LoadContent”的范围内创建的,然后在方法完成后删除。你需要做的是将纹理放在“类”级别,如下所示:

//outside of the method, and in general, should be placed near the top of the class    
Texture2D tileStart;
Texture2D tileCrossJunction;
Texture2D tileTJunction;
Texture2D tileCorner;
Texture2D tileHallway;
Texture2D tileDeadEnd;
Texture2D sqrPlayer;
Texture2D sqrBaddieSmall;
Texture2D sqrBaddie;
Texture2D sqrBaddieLarge;

protected override void LoadContent()
{
     spriteBatch = new SpriteBatch(GraphicsDevice);

     //be sure to remove Texture2D from these
     //this will insure that the "class" level variables are called
     tileStart = Content.Load<Texture2D>("tile_start");
     tileCrossJunction = Content.Load<Texture2D>("tile_crossjunction");
     tileTJunction = Content.Load<Texture2D>("tile_t-junction");
     tileCorner = Content.Load<Texture2D>("tile_corner");
     tileHallway = Content.Load<Texture2D>("tile_hallway");
     tileDeadEnd = Content.Load<Texture2D>("tile_deadend");
     sqrPlayer = Content.Load<Texture2D>("sqr_player");
     sqrBaddieSmall = Content.Load<Texture2D>("sqr_baddie_small");
     sqrBaddie = Content.Load<Texture2D>("sqr_baddie");
     sqrBaddieLarge = Content.Load<Texture2D>("sqr_baddie_large");
}

完成后,变量的“范围”将在类级别,您将能够在类中的其他方法中使用它们。

换句话说,没有办法从该方法外部访问方法中声明的变量(当然没有将它作为参数传递给另一个方法),你正在看的教程可能只是简短,并希望你“正确”地做到这一点。