- Home /
Why is my object loading as black instead of the saved color?
I'm writing a script to save and load a color that the user picks for the 3D object (could be a cube, cylinder, or sphere) via button presses, but when I try loading the object in, it's just black. I've double checked and the right RGB values are being saved and loaded, but the object just appears to be black. Also, for now, I'm just testing the loading output with a default color, which is red in my case. Why is this happening and how can I fix it?
Important Note: I made a "private Renderer rend;" at the top of the class, and then defined rend ("rend =...") in the void Start() section.
// 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 = rend.material.GetColor("_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 defaultColor = Color.red;
Color colorOfObject = new Color(PlayerPrefs.GetFloat("rValue", defaultColor.r),
PlayerPrefs.GetFloat("gValue", defaultColor.g), PlayerPrefs.GetFloat("bValue", defaultColor.b));
rend.material.SetColor("_Color", colorOfObject);
}
Answer by sean244 · Jan 16, 2019 at 12:09 AM
Your code works fine for me. I'm able to switch it between, red, green and blue, and I'm also able to save and load it as green.
Huh that's strange...:( Just a quick question, but does it matter what color I choose for the default?? I think I'm confused on how it's saving the user's chosen color if it's loading the default color. And this is what I see on my screen when I do the same process:
I honestly don't know, but I'm testing it on a 2d gameObject with a spriterenderer - whose default color is white - for what that's worth.
No worries, thanks for helping test it out!! I really appreciate it! I'm still a little confused on the logic of loading it though; isn't the new rendered material/color just the default RGB values?? I'm not sure how it's loading the color chosen by the user if the values are just being set to the default ones :O
Your answer
![](https://koobas.hobune.stream/wayback/20220612185830im_/https://answers.unity.com/themes/thub/images/avi.jpg)