[英]Convert an rgb string to a Color32
我有一個來自JSON文件的數據,該文件帶有一串color: '255,255,255'
為RGB的RGB字符串color: '255,255,255'
我想通過讀取字符串並將其轉換為color32為Unity中的顏色着色,但是我不知道該怎么做將它們轉換為Unity所需的格式: new Color32(255,255,255,255)
。
如何將字符串轉換為color32?
我已經成功地將其放入整數數組中,但是當我嘗試執行以下操作時, cannot apply indexing with [] to an expression of type int
錯誤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"
]
},
這是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"
]
}
以下是將其反序列化為( 從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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.