如何使用 PlayerPrefs 保存对象的颜色值?

我正在尝试根据用户选择的内容保存对象的颜色,并在按键时将它们加载回屏幕。在答案的帮助下,我设法找到了一种使用 PlayerPrefs 保存颜色 RGB 值的方法,但是,我不确定如何将“colorObject”设置为对象的当前颜色。我见过使用 new Color() 和预定义颜色集的解决方案,但我想保存用户选择的内容。有没有办法将“colorObject”设置为对象的当前颜色?


     /* Changing the color via key presses

     * 

     */


    if (Input.GetKeyDown(KeyCode.R))

    {

        rend.material.SetColor("_Color", Color.red);

    }

    if (Input.GetKeyDown(KeyCode.G))

    {

        rend.material.SetColor("_Color", Color.green);

    }

    if (Input.GetKeyDown(KeyCode.B))

    {

        rend.material.SetColor("_Color", Color.blue);

    }

}


// To add button elements to the visual interface

void OnGUI() 

{

    // Saving

    if (GUI.Button(new Rect(700, 330, 50, 30), "Save"))

    {

        // Saving the object's color 

        Color colorOfObject = new Color();

        PlayerPrefs.SetFloat("rValue", colorOfObject.r);

        PlayerPrefs.SetFloat("gValue", colorOfObject.g);

        PlayerPrefs.SetFloat("bValue", colorOfObject.b);

    }


    // Loading

    if (GUI.Button(new Rect(770, 330, 50, 30), "Load"))

    {

        Color colorOfObject = new Color(PlayerPrefs.GetFloat("rValue", 1F), PlayerPrefs.GetFloat("gValue", 1F), PlayerPrefs.GetFloat("bValue", 1F));

    }


开心每一天1111
浏览 154回答 2
2回答

斯蒂芬大帝

你可以这样做;public static void SaveColor (Color color, string key) {    PlayerPrefs.SetFloat(key + "R", color.r);    PlayerPrefs.SetFloat(key + "G", color.g);    PlayerPrefs.SetFloat(key + "B", color.b);}public static Color GetColor (string key) {    float R = PlayerPrefs.GetFloat(key + "R");    float G = PlayerPrefs.GetFloat(key + "G");    float B = PlayerPrefs.GetFloat(key + "B");    return new Color(R, G, B);}或者你可以将它的十六进制代码保存为字符串并加载它

慕慕森

在Awake中,获取对GameObject的渲染器的引用:private Renderer rend;void Awake() {&nbsp; &nbsp; rend = GetComponent<Renderer>();}将红色、蓝色、绿色和——如果需要的话——颜色的 alpha 通道保存为不同的浮动首选项:// Savingif (GUI.Button(new Rect(700, 330, 50, 30), "Save")){&nbsp; &nbsp; Color colorOfObject = rend.material.GetColor("_Color");&nbsp; &nbsp; PlayerPrefs.SetFloat("rValue", colorOfObject.r);&nbsp; &nbsp; PlayerPrefs.SetFloat("gValue", colorOfObject.g);&nbsp; &nbsp; PlayerPrefs.SetFloat("bValue", colorOfObject.b);&nbsp; &nbsp; PlayerPrefs.SetFloat("aValue", colorOfObject.a);}然后加载它,GetFloat相应地使用:// Loadingif (GUI.Button(new Rect(770, 330, 50, 30), "Load")){&nbsp; &nbsp; Color defaultColor = Color.red;&nbsp; &nbsp; Color colorOfObject = new Color(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PlayerPrefs.GetFloat("rValue", defaultColor.r),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PlayerPrefs.GetFloat("gValue", defaultColor.g),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PlayerPrefs.GetFloat("bValue", defaultColor.b),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PlayerPrefs.GetFloat("aValue", defaultColor.a)&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; rend.material.SetColor("_Color", colorOfObject);}
打开App,查看更多内容
随时随地看视频慕课网APP