为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
开心每一天1111 2022-07-23 09:03:02
我正在尝试根据用户选择的内容保存对象的颜色,并在按键时将它们加载回屏幕。在答案的帮助下,我设法找到了一种使用 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 interfacevoid 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));    }
查看完整描述

2 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

你可以这样做;


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

}

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


查看完整回答
反对 回复 2022-07-23
?
慕慕森

TA贡献1856条经验 获得超17个赞

在Awake中,获取对GameObject的渲染器的引用:


private Renderer rend;


void Awake() {

    rend = GetComponent<Renderer>();

}

将红色、蓝色、绿色和——如果需要的话——颜色的 alpha 通道保存为不同的浮动首选项:


// Saving

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

{

    Color colorOfObject = rend.material.GetColor("_Color");


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

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

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

    PlayerPrefs.SetFloat("aValue", colorOfObject.a);

}

然后加载它,GetFloat相应地使用:


// Loading

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

{

    Color defaultColor = Color.red;

    Color colorOfObject = new Color(

            PlayerPrefs.GetFloat("rValue", defaultColor.r),

            PlayerPrefs.GetFloat("gValue", defaultColor.g),

            PlayerPrefs.GetFloat("bValue", defaultColor.b),

            PlayerPrefs.GetFloat("aValue", defaultColor.a)

        );


    rend.material.SetColor("_Color", colorOfObject);

}


查看完整回答
反对 回复 2022-07-23
  • 2 回答
  • 0 关注
  • 153 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号