How can you use playerprefs to save colors? I know about int, string but there it seems like it cant save color.
Hey hubert,
this is an easy example (JavaScript) which shows how to save a color into a playerprefab and how to parse the playerprefab string afterwards back into a color that can be used as an material color for a gameobject.
function Start () {
//I've choosen one of the default colors (red)
PlayerPrefs.SetString("Color", Color.red.ToString());
ColorGO();
}
function ColorGO () {
var str_color : String;
str_color = PlayerPrefs.GetString("Color");
//Remove the header and brackets
str_color = str_color.Replace("RGBA(", "");
str_color = str_color.Replace(")", "");
//Get the individual values (red green blue and alpha)
var strings = str_color.Split(","[0] );
var outputcolor : Color;
for (var i = 0; i < 4; i++) {
outputcolor _= System.Single.Parse(strings*);*_
* }*
//apply the color to a gameobject
* this.gameObject.renderer.material.color = outputcolor;*
}
Codewarrior
private float r, g, b;
r = color.r;
g = color.g;
b = color.b;
PlayerPrefs.SetFloat("CarColorRed",color.r);
PlayerPrefs.SetFloat("CarColorGreen",color.g);
PlayerPrefs.SetFloat("CarColorBlue",color.b);
newVehicle.GetComponent().material.color
=new Color(PlayerPrefs.GetFloat(“CarColorRed”),PlayerPrefs.GetFloat(“CarColorGreen”),PlayerPrefs.GetFloat(“CarColorBlue”));
visite this answer.
Instead of writing your own methods, you could use unity’s ColorUtility class:
// Store single color
Color color;
PlayerPrefs.SetString("ColorKey", ColorUtility.ToHtmlStringRGB(color)); // without alpha
PlayerPrefs.SetString("ColorKey", ColorUtility.ToHtmlStringRGBA(color)); // with alpha
// Load single color
Color color;
ColorUtility.TryParseHtmlString("#" + PlayerPrefs.GetString("ColorKey"), out color);
// store color array
Color[] colors;
//// fill array with your colors ////
int numberOfColors = colors.Length;
for (int i = 0; i < numberOfColors; i++){
Color color = colors*;*
PlayerPrefs.SetString(“ColorKey” + i, ColorUtility.ToHtmlStringRGBA(color)); // with alpha
}
// load color array
Color[] colors = new Color[numberOfColors];
for (int i = 0; i < numberOfColors; i++){
ColorUtility.TryParseHtmlString(“#” + PlayerPrefs.GetString(“ColorKey” + i), out colors*);*
}
Edit: Adding “#” in front of colorHtmlString is required (see: Unity - Scripting API: ColorUtility.TryParseHtmlString)