gpt4 book ai didi

c# - 在 C# 中将 char 更改为 int 或 string

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:11 24 4
gpt4 key购买 nike

我是 C# sharp 的新手,这个问题的表述可能不是很好,但就这样吧。

我目前正在生成一个包含更多游戏对象的关卡。该 map 是通过解析文本文件生成的,这是我的字典。目前,由于 char 声明,如果对象的索引不超过 9,我的代码将完美运行。

我想知道如何将其更改为 int 或字符串格式 (A-Z) 的方法。我附上了我当前的“ map 生成器”的照片,并突出显示了 10,目前读作 1 和 0。enter image description here

private void CreateLevel() {

Tiles = new Dictionary<Point, TileScript>();

string[] mapData = ReadLevelText();

int mapX = mapData[0].ToCharArray().Length;
int mapY = mapData.Length;

Vector3 maxTile = Vector3.zero;

// Calculates the world start point, this is the top left corner of the screen, rememeber to use on the sprite the top left pivot point
Vector3 worldStart = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height));

for (int y = 0; y < mapY; y++) // the Y position
{

char[] newTiles = mapData[y].ToCharArray();

for (int x = 0; x < mapX; x++) // the X position
{
// Places the tile into the level
PlaceTile(newTiles[x].ToString(), x, y, worldStart);
}
}

maxTile = Tiles[new Point(mapX-1, mapY-1)].transform.position;

cameraMovement.SetLimit(new Vector3(maxTile.x + TileSize, maxTile.y - TileSize));
}

private void PlaceTile(string tileType, int x, int y, Vector3 worldStart) {

int tileIndex = int.Parse(tileType);

// Creates a new tile and makes a reference to that tile in the newTile variable
TileScript newTile = Instantiate(tilePrefabs[tileIndex]).GetComponent<TileScript>();

// Uses the new tile variable to change the position of the tile

newTile.Setup(new Point(x, y), new Vector3(worldStart.x + (TileSize * x), worldStart.y - (TileSize * y), 0));

Tiles.Add(new Point(x,y), newTile);

}

最佳答案

您使用的数据格式无法解析。

想一想,无法判断这些数字中的哪一个应该被解释为一对“10”或单个“1”甚至三个“101”。

在这些情况下,我会建议重做您的文件格式以使用字符而不是数字,让您可以使用更多符号,和/或我强烈建议使用 delimiter,例如 , 你的每一个之间的字符。 CSV(逗号分隔值)文件格式正是这样做的。

您可以在 Excel、Numbers (mac)、LibreOffice 等电子表格程序或 Google 表格等在线电子表格工具中创建关卡。您可以通过在单元格中填写值来完成此操作,然后在完成后导出/“另存为”.csv 文件。

您可以使用类似 CsvHelper 的 .NET 库解析 .csv 文件(我强烈推荐在现实世界中使用它来读取 CSV 数据)

或者,如果您想以快速而肮脏的方式进行操作,您可以使用类似 File.ReadAllLinesTrim() 每行的方式将文件读入内存从文件中,然后使用 Split(',') 将每一行拆分为其值。然后,您可以遍历二维数组,如果您愿意,可以将其映射到另一个值!

关于c# - 在 C# 中将 char 更改为 int 或 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com