【问题标题】:Convert an rgb string to a Color32将 rgb 字符串转换为 Color32
【发布时间】:2018-08-10 16:45:44
【问题描述】:

我有来自 JSON 文件的数据,其中包含一堆格式为 color: '255,255,255' 的 RGB 字符串 - 我想通过读取该字符串并将其转换为 color32 来为 Unity 中的内容着色,但我无法弄清楚如何将这些转换为 Unity 需要的格式:new Color32(255,255,255,255)

如何将字符串转换为 color32?

我已经成功地将它放入一个整数数组中,但是当我尝试这样做时,我得到了一个cannot apply indexing with [] to an expression of type int 错误:

int awayColor = team2Data.colors[0];
awayBG.color = new Color32(awayColor[0],awayColor[1],awayColor[2],255);

具有如下所示的数据结构:

"colors": [
        [225,68,52],
        [196,214,0],
        [38,40,42]
      ]

我用来解析 JSON 的类是:

[System.Serializable]
    public class TeamData
    {
        public List<Team> teams = new List<Team>();
    }

    [System.Serializable]
    public class Team
    {
        public int[] colors;
        public string id;
    }

我正在使用的功能是:

string filePath = Path.Combine(Application.dataPath, teamDataFile);
//string filePath = teamDataFile;
if(File.Exists(filePath))
{
    string dataAsJson = File.ReadAllText(filePath);
    //Debug.Log(dataAsJson);
    teamData = JsonUtility.FromJson<TeamData>(dataAsJson);
}
else
{
    Debug.Log("Cannot load game data!");
}

原始 JSON 如下所示:

{
      "id": "ATL",
      "colors": [
        "225,68,52",
        "196,214,0",
        "38,40,42"
      ]
    },

【问题讨论】:

  • 可以发完整的json数据吗?
  • 如果您已经有了字符串,并且没有程序员要求的数据,我将使用逗号分隔符拆分字符串,然后通过从第一个字符串中删除 color: ' 来清理第一个和最后一个值, 和 ' 来自最后一个字符串,将所有 3 转换为一个字节并将其传递给构造函数。第 4 个参数是 alpha,如果你不存储它,那么它可能是完全不透明的,所以将 255 传递给 a。
  • AwayColors 是 int,而不是 int[],这就是您收到该错误的原因。
  • 您是否尝试将awayColor[x] 转换为字节?
  • 我尝试将其声明为int[] 并得到cannot implictly convert type int to int[] - 即使在我的课堂上我将颜色设置为public int[] colors;。我认为这是问题所在 - 因为它是一个多维数组,它实际上将顶级数组记录为 [0,0,0] 而没有子数组。也许我需要另一个类来解析数组的第二维?

标签: c# unity3d colors tryparse


【解决方案1】:

这里是Color32 构造函数:

public Color32(byte r, byte g, byte b, byte a) {...}

它以byte 为参数而不是int。您将int 传递给它,因为awayColor 变量是int。此外,awayColor 变量不是数组,但您正在执行 awayColor[0]awayColor[1]


给定下面的json:

{
      "id": "ATL",
      "colors": [
        "225,68,52",
        "196,214,0",
        "38,40,42"
      ]
}

下面是一个反序列化的类(Generated from this):

[Serializable]
public class ColorInfo
{
    public string id;
    public List<string> colors;
}

检索颜色 json 值

string json = "{\r\n      \"id\": \"ATL\",\r\n      \"colors\": [\r\n        \"225,68,52\",\r\n  
ColorInfo obj = JsonUtility.FromJson<ColorInfo>(json);

获取列表中的第一个颜色并修剪它

string firstColor = obj.colors[0];
firstColor = firstColor.Trim();

用逗号将其拆分为3,然后将其转换为字节数组

byte[] color = Array.ConvertAll(firstColor.Split(','), byte.Parse);

从颜色字节数组创建Color32

Color32 rbgColor = new Color32(color[0], color[1], color[2], 255);

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 2020-11-13
    • 2013-12-24
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多