Rum*_*ata 3 c# colors unity-game-engine
如何使用HEX值更改Unity中的按钮颜色?
我尝试了这个,但它不起作用,也许我在这里犯了一个错误:
btn.image.color = ColorUtility.TryParseHtmlString(DADADAFF, out color);
Run Code Online (Sandbox Code Playgroud)
您将bool分配给Color(btn.image.color).
ColorUtility.TryParseHtmlString返回bool没有Color如果成功.您将获得第二个参数中的输出颜色,然后将其分配给Button.如果ColorUtility.TryParseHtmlString返回true,则仅使用输出颜色.
下面是代码应该是什么样子:
string htmlValue = "#FF0000";
Button btn = GetComponent<Button>();
Color newCol;
if (ColorUtility.TryParseHtmlString(htmlValue, out newCol))
{
btn.image.color = newCol;
}
Run Code Online (Sandbox Code Playgroud)
要将颜色转换回十六进制:
Color newCol = Color.red;
string htmlValue = ColorUtility.ToHtmlStringRGBA(newCol);
Run Code Online (Sandbox Code Playgroud)
所以没有办法只分配Hex颜色而不检查它是否可以先转换为RGB?
有.删除if声明.
ColorUtility.TryParseHtmlString(htmlValue, out newCol);
btn.image.color = newCol;
Run Code Online (Sandbox Code Playgroud)
不要这样做,因为你的Color结果可能是错的.您应该if像我在第一个代码中所做的那样处理这个问题.
您可以使用十六进制数字:
btn.image.color = new Color32(0xDA, 0xDA, 0xDA, 0xFF);
Run Code Online (Sandbox Code Playgroud)