首页 > 解决方案 > How can I use PlayerPrefs to save the color values of the object?

问题描述

I'm trying to save the object's color based on what the user chooses and the load them back onto the screen on a key press. With some help from the answers, I managed to find a way to save color RGB values with PlayerPrefs, however, I'm not sure how to set "colorObject" to the object's current color. I've seen solutions where new Color() and predefined sets of colors are used, but I want to save what the user chooses. Is there a way to set "colorObject" to the current color of the object?

     /* 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));
    }

标签: c#objectunity3dcolors

解决方案


你可以这样做;

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);
}

或者你可以将它的十六进制代码保存为字符串并加载它


推荐阅读