【发布时间】: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