从JSON加载颜色字符串并转换为float

问题描述 投票:0回答:1

我正在尝试像这样加载JSON

public static string codename = "test";
var jsonTextFile = Resources.Load<TextAsset>("songs/" + codename.ToLower() + "/" + codename.ToLower() + ".json");

在JSON文件中,有一个名为lyricsColor的字符串,看起来像这样

{
  "lyricsColor": "#FF0000"
}

我想知道如何获取字符串,将其转换为RGB float以将其应用于.color =

public Image beattexture;
beattexture.color = new Color(lyricsColor);

这是我到目前为止尝试过的:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class Pictobar : MonoBehaviour

{
    public static string codename = "Umbrella";
    var jsonTextFile = Resources.Load<TextAsset>("songs/" + codename.ToLower() + "/" + codename.ToLower() + ".json");
    public Image beattexture;
[Serializable]
    public class songJson
{
    public string lyricsColor;

    public static songJson CreateFromJSON(string lyricsColor)
    {
        return JsonUtility.FromJson<songJson>(lyricsColor);
    }

    var lyricsColor = lyricsColor.ToFloat();
}
    void Start()
    {
        // Set pictobeat color
        beattexture.color = new Color(lyricsColor);
    }

    void Update()
    {

    }
}
c# json unity3d rgb
1个回答
0
投票

您不需要/不想将给定的字符串转换为float

您可以使用ColorUtility.TryParseHtmlString解析十六进制(html)颜色格式,例如

ColorUtility.TryParseHtmlString

然后像例如使用它

[Serializable]
public class songJson
{
    public string lyricsColor;

    // Note avoid/be careful with shadowing your fields
    // the name lyricsColor as parameter here is confusing!
    public static songJson CreateFromJSON(string json)
    {
        return JsonUtility.FromJson<songJson>(json);
    }

    public bool TryGetColor(out Color color)
    {
        color = Color.black;
        if(ColorUtility.TryParseHtmlString(lyricsColor, out color))
        {
             return true;
        }

        Debug.LogWarning($"Could not parse {lyricsColor}!");
        return false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.