0

我正在尝试将一个新的 List 变量设置为类的方法返回值的结果,有点像这样:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    public static SpriteBatch spriteBatch;

    // ...stuff...

    // Class initialization
    private Map map = new Map() { Width = 10, Height = 10, TileWidth = 16, TileHeight = 16 };

    // Variable declaration
    List<Vector2> blockPos = new List<Vector2>();
    blockPos = map.generateMap(); // Doesn't work

    Texture2D dirtTex;

    // ...more stuff...
}

我认为它不起作用,因为它不在方法内,我可以将它放在我的 Update() 方法中,但它运行每一帧,我只想这样做一次。

尝试上述代码会导致 3 个错误:

'Deep.Game1.blockPos' is a 'field' but is used like a 'type'
Invalid token '=' in a class, struct, or interface member declaration
'Deep.Game1.map' is a 'field' but is used like a 'type'

地图类:

class Map
{
    // Variable declaration
    public int Width { get; set; } // Width of map in tiles
    public int Height { get; set; } // Height of map in tiles
    public int TileWidth { get; set; }
    public int TileHeight { get; set; }
    Random rnd = new Random();

    // Generate a list of Vector2 positions for blocks
    public List<Vector2> generateMap()
    {
        List<Vector2> blockLocations = new List<Vector2>();

        // For each tile in the map...
        for (int w = 0; w < Width; w++)
        {
            for (int h = 0; h < Height; h++)
            {
                // ...decide whether or not to place a tile...
                if (rnd.Next(0, 1) == 1)
                {
                    // ...and if so, add a tile at that location.
                    blockLocations.Add(new Vector2(w * TileWidth, h * TileHeight));
                }
            }
        }

        return blockLocations;
    }
}

我尝试使用构造函数,但是尽管没有错误,但其中的代码似乎没有运行:

public void getPos()
{
    blockPos = map.generateMap();
}
4

1 回答 1

0

通过声明变量,然后在 LoadContent() 方法中将其设置为 map.generateMap() 来修复:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    public static SpriteBatch spriteBatch;

    // ...

    // Class initialization
    private Map map = new Map() { Width = 10, Height = 10, TileWidth = 16, TileHeight = 16 };

    // Variable declaration
    List<Vector2> blockPos = new List<Vector2>();

    Texture2D dirtTex;

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        dirtTex = Content.Load<Texture2D>("dirt");

        blockPos = map.generateMap();
    }

    // ...
}
于 2013-10-22T21:10:59.407 回答