繁体   English   中英

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

[英]Change char to int or string in C#

我对 C# 很陌生,这个问题的表述可能不是很好,但在这里。

我目前正在生成一个包含更多游戏对象的关卡。 map 是通过解析文本文件生成的,这是我的字典。 目前,如果 object 的索引没有 go 超过 9,我的代码可以完美运行,因为 char 声明。

我想知道如何将其更改为 int 或字符串格式(AZ)的方法。 我附上了一张我当前的“地图生成器”的照片,并突出显示了 10,目前读取为 1 和 0。 在此处输入图像描述

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”。

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

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

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

或者,如果您想以快速而肮脏的方式进行操作,您可以使用File.ReadAllLines之类的方法将文件读入 memory , Trim()文件中的每一行,然后使用Split(',')分割每一行融入其价值观。 然后,您可以遍历您的二维数组,并将 map 迭代到另一个值,如果您愿意的话!

我会创建一个字符串数组来保存符号,首先——可能是“A”-“Z”。 然后,将 char[] 更改为 unsigned int[] (以及支持它的其他更改,例如 ToCharArray() 调用)。

然后,当您放置瓷砖时,而不是传递 newTiles[x].ToString(),而是传递符号 [newTiles[x]]。

(说实话,如果可以的话,我可能会将符号数组设为 char,并更改 PlaceTile() 的签名)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM