我正在尝试将一个新的 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();
}